How to get all checkout fields from WooCommerce?

前端 未结 3 1908
甜味超标
甜味超标 2021-02-10 04:13

I like to get all available checkout fields, including third party ones:

$fields = WC()->checkout()->checkout_fields;

returns a fatal err

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-10 04:51

    I know I'm late to the party, but I was looking for an exact feature and accepted answer was not satysfying for me, so I digged into this.

    As question owner said, he needs to get all available checkout fields on admin area (in his plugin).

    He cant do this stright away because there is no checkout available at that point (and no customer or even WooCommerce session).

    So the solution is to fake session and customer so checkout will be available in the admin area (with default user data).

    /*
    * WooCommerce does not load session class on backend, so we need to do this manually
    */
    if ( ! class_exists( 'WC_Session' ) ) {
        include_once( WP_PLUGIN_DIR . '/woocommerce/includes/abstracts/abstract-wc-session.php' );
    }
    
    /*
    * admin_init hook for testing purposes
    */
    add_action('admin_init', function(){
        /*
        * First lets start the session. You cant use here WC_Session directly
        * because it's an abstract class. But you can use WC_Session_Handler which
        * extends WC_Session
        */
        WC()->session = new WC_Session_Handler;
    
        /*
        * Next lets create a customer so we can access checkout fields
        * If you will check a constructor for WC_Customer class you will see
        * that if you will not provide user to create customer it will use some
        * default one. Magic.
        */
        WC()->customer = new WC_Customer;
    
        /*
        * Done. You can browse all chceckout fields (including custom ones)
        */
        var_dump(WC()->checkout->checkout_fields);
        die();
    });
    

提交回复
热议问题