Display Yoast meta-description `wpseo_desc` within loop of categories and fail silently if no data is set

I want to output the Yoast SEO category meta-description within a custom loop. Current code (below) works if there is a meta-description present. However, if no category meta-description is set it breaks.

Is there a better way to write this so that it fails silently if no meta-description is set

?php 
$popular_topics = get_field('popular_topics');
if( $popular_topics ):
      foreach( $popular_topics as $topic ): 
        $id    = $topic-term_id;
        $meta  = get_option( 'wpseo_taxonomy_meta' );
        $meta_desc   = $meta['category'][$id]['wpseo_desc'];
        ?
          p class=my-paragraph
            ?php echo esc_html( $meta_desc ); ?
          /p
      ?php endforeach;
endif; ?

Edit, wrapped in a simple !empty if statement

if(!empty( $meta['category'][$id]['wpseo_desc'] )) {
 echo $meta['category'][$id]['wpseo_desc'];
}
else {
 echo Meta not present;
}

Topic plugin-wp-seo-yoast php Wordpress

Category Web


You can just check if $meta and $meta_desc exist. If not, don't echo anything.

$popular_topics = get_field('popular_topics');

if ( $popular_topics ) : 

    foreach ( $popular_topics as $topic ) : 

        $id = $topic->term_id;
        $meta = get_option('wpseo_taxonomy_meta');

        if ( $id && ( $meta && !empty($meta) ) ) : 

            $meta_desc = $meta['category'][$id]['wpseo_desc'];

            if ( $meta_desc ) : ?>

                <p class="my-paragraph">
                    <?php echo esc_html( $meta_desc ); ?>
                </p>

                <?php

            endif;

        endif;

    endforeach;

endif;

Wrap in a !empty statement

if(!empty( $meta['category'][$id]['wpseo_desc'] )) {
 echo $meta['category'][$id]['wpseo_desc'];
}
else {
 echo "Meta not present";
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.