Search code examples
phpwordpresswoocommercehook-woocommercewoocommerce-rest-api

Woocommerce 5.4.1: How to Add Hook to a specific Post on Archive Page - Shop Page


After a lot of search and nothing found, how can I apply this Hook just for a Single Post on the Archive Page?

The goal is to use different Text for different Post, but in this position of the post. Ex. 10%, 20%, 30%

As you see on the picture, the function is applied for every Post and this is not the goal.

Maybe I must use the Post ID to select and use the function for the specific Post.

// define the woocommerce_before_shop_loop_item_title callback 
function action_woocommerce_before_shop_loop_item_title(  ) { 
        echo "<div>
        <small>Get a discount of 10% on any item</small>
      </div>";
}; 
   // add the action 
add_action( 'woocommerce_before_shop_loop_item_title', 'action_woocommerce_before_shop_loop_item_title', 10, 0 ); 

Result of the script above:

enter image description here


Solution

  • Yes you can use product ID to add text to specific post

    // define the woocommerce_before_shop_loop_item_title callback 
    function action_woocommerce_before_shop_loop_item_title(  ) { 
    global $post;
    if($post->ID == your_post_id){
            echo "<div>
            <small>Get a discount of 10% on any item</small>
          </div>";}
    }; 
       // add the action 
    add_action( 'woocommerce_before_shop_loop_item_title', 'action_woocommerce_before_shop_loop_item_title', 10 );