简体   繁体   中英

Show custom field between product name and star ratings on WooCommerce archive pages

I want to add a custom field on product cards like below. The code I wrote for this works, but the custom field I added appears above the category name.

I want it to appear between the stars and the product name as I showed in the picture.

我想在星星和产品名称之间显示它

The code I am currently using for this is

add_action( 'woocommerce_after_shop_loop_item_title', 'woo_show_product_id', 20);
function woo_show_product_id() {
    global $product;

    echo $product->id;
}

How can I do that or what adjustment is needed for this?

In includes/wc-template-hooks.php we can find:

add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5 );

So change priority from 20

add_action( 'woocommerce_after_shop_loop_item_title', 'woo_show_product_id', 20);

To 4 to display your custom field just before the star ratings

add_action( 'woocommerce_after_shop_loop_item_title', 'woo_show_product_id', 4 );

Priority: Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. Default value: 10

Note: use $product->get_id(); as of WooCommerce 3.0


So to answer your question, you can use

  1. via woocommerce_after_shop_loop_item_title
function woo_show_product_id() {
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get Product ID
        echo $product->get_id();
    }
}
add_action( 'woocommerce_after_shop_loop_item_title', 'woo_show_product_id', 4 );

OR

some other hook from includes/wc-template-hooks.php

add_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );

And then you get with priority 11

  1. via woocommerce_shop_loop_item_title
function woo_show_product_id() {
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get Product ID
        echo $product->get_id();
    }
}
add_action( 'woocommerce_shop_loop_item_title', 'woo_show_product_id', 11 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM