简体   繁体   中英

Output a custom shortcode for a specific product category in WooCommerce

I am trying to add an extra button to my products on my shop page but only to a specific category. I have gotten this far but I cannot seem to call it up right.

if (!function_exists('add_accessory_button')){
function add_accessory_button() {
  global $product;
  $product_cat = $product->product_cat;

  if( has_term( 'dealqualify',$product_cat ) && in_the_loop() ) {
    $link = get_post_meta( $product->ID, ‘acc_link’, true );
    echo do_shortcode('<br>[button link="' . esc_attr($link) . '"]View Accessory[/button]');
} }
add_action('woocommerce_after_shop_loop_item','add_accessory_button');
}

Any help to pinpoint my mistake would be appreciated.

There is a lot of errors in your code

You need to set has_term() this way in your condition to make it work:

has_term( 'dealqualify', 'product_cat', $product->get_id() )

Also for the product ID do it this way: $product->get_id() ... I have try to correct the others errors too...

So your code should be something like:

if ( ! function_exists('add_accessory_button')){

    function add_accessory_button() {
        global $product;
        if( has_term( 'dealqualify', 'product_cat', $product->get_id() ) && in_the_loop() ) {
            $link = get_post_meta( $product->get_id(), 'acc_link', true );
            echo '<br>' . do_shortcode("[button link='$link']View Accessory[/button]");
    }
    add_action('woocommerce_after_shop_loop_item','add_accessory_button');
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This should work now…

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