0

我已经创建了自定义文本字段,但我无法使用操作挂钩在单个产品页面上输出它......

如果有人可以提供解决方案,我将非常感激?

我的代码(functions.php):

    // Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );


function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  echo '<div class="options_group">';

  // Custom fields will be created here...

    woocommerce_wp_text_input( 
    array( 
        'id'          => '_text_field', 
        'label'       => __( 'My Text Field', 'woocommerce' ), 
        'placeholder' => 'http://',
        'desc_tip'    => 'true',
        'description' => __( 'Enter the custom value here.', 'woocommerce' ) 
    )
);

  echo '</div>';

}

function woo_add_custom_general_fields_save( $post_id ){

// Text Field
    $woocommerce_text_field = $_POST['_text_field'];
    if( !empty( $woocommerce_text_field ) )
        update_post_meta( $post_id, '_text_field', esc_attr( $woocommerce_text_field ) );

}


add_action( 'woocommerce_single_product_summary', 'output_custom_fields' );


function output_custom_fields() {
    echo get_post_meta( $post->ID, '_text_field', true );
}

谢谢!丹尼斯

4

1 回答 1

1

As @MirzaP says in comment, $post is not defined in the function output_custom_fields(). So $post->ID can not work

To make it work (be able to get the post object in the function)

function output_custom_fields() {
    global $post;

    echo get_post_meta( $post->ID, '_text_field', true );
}

Don't forget the third parameter of your hooked action, that will sets the priority. These priorities can be found in the Woocommerce template, use the right priority according of where you want to place your meta data.

/**
     * woocommerce_single_product_summary hook
     *
     * @hooked woocommerce_template_single_title - 5
     * @hooked woocommerce_template_single_price - 10
     * @hooked woocommerce_template_single_excerpt - 20
     * @hooked woocommerce_template_single_add_to_cart - 30
     * @hooked woocommerce_template_single_meta - 40
     * @hooked woocommerce_template_single_sharing - 50
 */

So if you want your custom data to be shown right after the price, you need to set the priority with an integrer between 11 and 19

add_action('woocommerce_single_product_summary', 'output_custom_fields', 15);
于 2016-10-24T14:47:54.827 回答