Доступ к объекту Order в пользовательской функции из метабокса Woocommerce - PullRequest
0 голосов
/ 03 октября 2018

Я очень новичок в Wordpress и Woocommerce.Ниже приведена часть моего кода, которую я использую для добавления настраиваемого метабокса для упорядочивания отдельных страниц администратора:

add_action('add_meta_boxes', 'new_meta_box');

function new_meta_box(){
add_meta_box(
    'new_meta_box',
    'New Meta Box',
    'new_meta_box_button',
    'shop_order',
    'side',
    'high'
);
}

function new_meta_box_button(){

submit_button('New Meta Box Button', 'primary','new_meta_box_button');      

global $post;
$order_id = $post->ID;
$order = wc_get_order($order_id);
$order_number = absint($order->get_order_number());

button_action($order);  
}   

add_action('save_post','button_action');

function button_action($order){
 //unbale to access $order here

if(!isset($_POST['new_meta_box_button'])){
        return;
    }

 get_value($order);
 }

function get_value($order){

//unable to access $order here
// var_dump($order) shows nothing
$order_id = $order->get_order_number();

$json = get_json($order_id);

$option_value = get_option( 'option_meta_key' );

}

В этом коде, если я использую настраиваемую функцию get_the_order() в get_order_details, она работает.Моя проблема в том, что мне нужен доступ к объекту WC_Order $order в различных функциях по всему файлу.

Это все на стороне администратора с уже существующим заказом, поэтому новый заказ не создается.Мне нужны определенные детали заказа в одной функции, такие как детали доставки и счета в другой функции ... и т. Д. И т. Д.

Что я делаю не так?Как я могу получить доступ к объекту заказа из внешней пользовательской функции?

Ответы [ 2 ]

0 голосов
/ 03 октября 2018

Вы все еще не объясняете, что вы хотите сделать с этим метабоксом на страницах администрирования заказа.

Следующий код, основанный на вашем коде, покажет вам путь (с реальным функционалом$order):

// Add a new custom meta box to Admin single order pages
add_action('add_meta_boxes', 'new_meta_box');
    function new_meta_box(){
    add_meta_box( 'new_meta_box',
        __('New Meta Box', 'woocommerce'),
        'new_meta_box_content',
        'shop_order', 'side', 'high'
    );
}

// The content of this new metabox
function new_meta_box_content(){
    global $post; // <=== Alway at the beginning

    // Get an instance of the WC_Order Object
    $order = wc_get_order( $post->ID );

    // TESTING an external custom function (with the WC_Order object as argument)
    echo get_formatted_order_key( $order );

    // Example (testing): Displaying a text field
    woocommerce_wp_text_input( array(
        'id'          => '_my_text_field1',
        'type'        => 'text',
        'label'       => __( 'My field 1', 'woocommerce' ),
        'placeholder' => __( 'My placeholder text 1', 'woocommerce' ),
        'description' => __( 'My Custom description 1: your explanations.', 'woocommerce' ),
        'desc_tip'    => true,
    ) );

    // The nonce field (security): Always when you submit data from custom form fields
    echo '<input type="hidden" name="my_fields_nonce" value="' . wp_create_nonce() . '">';

    // Not really needed as the default "Update" button does the same.
    submit_button(__('Submit'), 'primary', 'new_meta_box_button' ); //  <=== To be removed
}

// Saving the text field value only from shop orders post type admin pages
add_action('save_post_shop_order','save_new_meta_box_content');
function save_new_meta_box_content( $post_id ){
    if ( ! isset( $_POST[ 'my_fields_nonce' ] ) ) {
        return $post_id;
    }

    if ( ! wp_verify_nonce( $_REQUEST[ 'my_fields_nonce' ] ) ) {
        return $post_id;
    }

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return $post_id;
    }

    if ( ! current_user_can( 'edit_shop_order', $post_id ) ) {
        return $post_id;
    }

    // Everything is secured, we can save the value
    if ( isset( $_POST[ '_my_text_field1' ] ) ) {
        update_post_meta( $post_id, '_my_text_field1', sanitize_text_field( $_POST[ '_my_text_field1' ] ) );
    }
}


// Custom external function with the WC_Order object as argument
function get_formatted_order_key( $order ){
    if( is_a($order, 'WC_Order') && $order_key = $order->get_order_key() ){
        $output = '<p><strong>Order key: </strong>'.$order_key.'</p>';
    } else {
        $output = '<p style="font-weight:bold; color:red;">Something is wrong!</p>';
    }
    return $output;
}

Код помещается в файл function.php вашей активной дочерней темы (активной темы).Проверено и работает.

enter image description here

0 голосов
/ 03 октября 2018

WC_ORDER содержит все детали выставления счетов и доставки.

...