We can add a meta description for a single Custom Post and taxonomy for this CPT by adding a simple code to functions.php file inside your theme.

if ( ! function_exists( 'wpctMetaDescription' ) ) {
    function wpctMetaDescription() {
        global $post;
        $meta_description_limit = 158; // limit of meta description
        if ( is_singular('my_custom_post_type') ) {
            $desc_post = strip_tags( $post->post_content );
            $desc_post = strip_shortcodes( $post->post_content );
            $desc_post = str_replace( array("\n", "\r", "\t"), ' ', $desc_post );
            $desc_post = mb_substr( $desc_post, 0, $meta_description_limit, 'utf8' );
            echo '<meta name="description" content="' . $desc_post . '" />' . "\n";
        }
        if ( is_tax('my_custom_post_type_taxonomy') ) {
            $category_description = strip_tags( category_description() );
            $desc_cat = strip_shortcodes( $category_description );
            $desc_cat = str_replace( array("\n", "\r", "\t"), ' ', $desc_cat );
            $desc_cat = mb_substr( $desc_cat, 0, $meta_description_limit, 'utf8' );
             echo '<meta name="description" content="' . $desc_cat . '" />' . "\n";
        }
    }
    add_action( 'wp_head', 'wpctMetaDescription');
}

You don’t need to use plugins like Yoast SEO for this feature. Above code generates meta description this way:

  • CPT single – beginning of the post content
  • CPT taxonomy – description field
Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *