Search code examples
phpwordpresswoocommercehook-woocommercewoocommerce-theming

WooCommerce how to show Information on Product Archive IF by Certain Author


I want to echo some text before the cart on a product archive page (shop listings) but ONLY on the products that are by a certain author.

I have this code which shows the information I want where I want it:

add_filter( 'woocommerce_loop_add_to_cart_link', 'tomich_add_melody_vendor', 10, 3 );
function tomich_add_melody_vendor ( $add_to_cart_html, $product, $args )
{
    $before = 'Shop: <img class="vendor-image-tomich" src="https://melodypayne.com/wp-content/uploads/2019/06/cropped-Melody-Payne-Store-Logo-Pic-2019.png" alt="Melody Logo"><span class="tomich-shop-title"><a href="/shop/melodypayne">Melody Payne</a></span></br></br>'; // Some text or HTML here
    $after = ''; // Add some text or HTML here as well

    
    return $before . $add_to_cart_html . $after;
}

But now I need to figure out how to restrict it to just show on products by a certain author, either by nickname or ID.

I tried some variations of this code but none of it worked.

$author_id = get_post_field('post_author', get_queried_object_id());

if (get_the_author_meta('display_name', $author_id) === 'vivian') {
    // do something
}

Solution

  • You're passing $product to your custom callback function, so you could use it to get the author info like so:

    add_filter('woocommerce_loop_add_to_cart_link', 'tomich_add_melody_vendor', 10, 3);
    
    function tomich_add_melody_vendor($add_to_cart_html, $product, $args)
    {
    
      $author_nickname = get_the_author_meta('nickname', $product->post->post_author);
    
      // OR
      // $author_id = get_the_author_meta('ID', $product->post->post_author);
    
      // OR
      // $author_name = get_the_author_meta('display_name', $product->post->post_author);
    
      // You could also get the author with other paramaeters like:
      // display_name
      // first_name
      // ID
      // last_name
      // nickname
    
      if ($author_nickname == "vivian") { // pass the name you want
    
        $before = 'my custom element before'; // Some text or HTML here
    
        $after = 'my custom element after'; // Add some text or HTML here as well
    
    
        return $before . $add_to_cart_html . $after;
    
      } else {
    
        return $add_to_cart_html;
      }
    
    }