📌  相关文章
📜  在 achive 页面上的产品标题后添加自定义文本 - TypeScript 代码示例

📅  最后修改于: 2022-03-11 14:48:22.306000             🧑  作者: Mango

代码示例1
//Register the product custom field

/// for add this in advance tab we need to use 'woocommerce_product_options_advanced'
add_action( 'woocommerce_product_options_general_product_data', 'my_woocommerce_product_subheading' );

function my_woocommerce_product_subheading() {
    $args = array(
        'label' => 'Subheading', // Text in Label
        'placeholder' => 'My Subheading',
        'id' => 'product_subheading', // required
        'name' => 'product_subheading',
        'desc_tip' => 'The product subheading',
    );
    woocommerce_wp_text_input( $args );
}

//Save the custom field as product custom post meta
add_action( 'woocommerce_process_product_meta', 'my_woocommerce_save_product_subheading' );

function my_woocommerce_save_product_subheading( $post_id ) {
    $product = wc_get_product( $post_id );
    $title = isset( $_POST['product_subheading'] ) ? $_POST['product_subheading'] : '';
    $product->update_meta_data( 'product_subheading', sanitize_text_field( $title ) );
    $product->save();
}

//Display the custom field on product page loop below the title
add_action( 'woocommerce_after_shop_loop_item_title', 'subheading_display_below_title', 2 );
function subheading_display_below_title(){
    global $product;

    // Get the custom field value
    $subheading = get_post_meta( $product->get_id(), 'product_subheading', true );

    // Display
    if( ! empty($subheading) ){
        echo '

'.$subheading.'

'; } }