Search code examples
phpwordpresswoocommerceproductmeta-tags

Display product titles as kewords from WooCommerce product category archives


I would like to get product names from WooCommerce product category archive pages to use them as keywords in an HTML head meta tag.

Here is my code:

<meta name="keywords" content="<?php
if( is_product_category() ){
    foreach ($loop_items as $item);
    $kewords .= ','. $product->get_name();
echo $kewords;
} else
    $key = get_post_meta( get_the_id(), 'keywords', true);
    if( ! empty( $key )  ){
        $meta_key = esc_html($key);
        echo  $meta_key ;
}
?>"/>

Solution

  • You need to loop through WP_Query posts to display product titles as keywords like:

    <meta name="keywords" content="<?php
    if( is_product_category() ){
        global $wp_query;
    
        if ( isset($wp_query->posts) ) {
            $post_titles = array(); // Initializing
    
            // Loop through product post
            foreach ($wp_query->posts as $post) {
                $post_titles[] = $post->post_title;
            }
            // Display the array as a comma separated string of product titles
            echo implode(',', $post_titles); 
        }
    } else
        $key = get_post_meta( get_the_id(), 'keywords', true);
        if( ! empty( $key )  ){
            $meta_key = esc_html($key);
            echo  $meta_key ;
    }
    ?>"/>
    

    It should work.