skip to Main Content

I want to display de category description in a meta tag but my code does not return the category description but the description of the first product of the store page

<head>
    <meta name="description" content="<?php
    if( is_product_category() ){
        $catID = get_the_category();
        echo category_description( $catID[0] );
    } else 
        $description = get_the_content();
        if ( $description) {
            echo wp_strip_all_tags($description);
        }
    ?>"/>

enter image description here

enter image description here

2

Answers


  1. There are some mistakes in your code:

    • To get the product category term ID used in a product category archive page use the WordPress function get_queried_object_id(),
    • There are missing brackets after the ELSE statement,
    • You should also use WordPress is_singular() conditional function to target single post and product pages,

    Try to use the following instead:

    <head>
        <meta name="description" content="<?php
        // Target Product category archives
        if( is_product_category() ) {
            $description = category_description( get_queried_object_id() );
        } 
        // Target single post and product pages
        elseif ( is_singular( array( 'post', 'product' ) ) ) {
            $description = get_the_content();
        }
        // Display description
        if ( isset($description) && $description ) {
            echo wp_strip_all_tags( $description );
        }
        ?>"/>
    

    It should work.

    If you want to target only single product pages (but not blog posts too), replace the line:

    elseif ( is_singular( array( 'post', 'product' ) ) ) {
    

    with:

    elseif ( is_product() ) {
    
    Login or Signup to reply.
  2. get_queried_object_id() will retrieves the current queried id.

    $category->term_id Accesses the ID of the current category, which is then used to fetch the category description.

    get_the_excerpt() function retrieves the excerpt for the current post. If the post does not have a manual excerpt, it generates one from the post content.

    <head>
        <meta name="description" content="<?php
        
        if ( is_product_category() ) {
            $category_term_id = get_queried_object_id();
            $description = category_description( $category_term_id ); 
        } else {
            $description = get_the_excerpt();
        }
    
        if ( $description ) {
            echo wp_strip_all_tags(truncate_text($description));
        }
        ?>"/>
    

    Function for truncate the description to 160

    function truncate_text($text, $max_length = 160) {
        if (strlen($text) > $max_length) {
            $text = substr($text, 0, $max_length) . '...';
        }
        return $text;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search