Related content based on category name

You have a couple of flaws here and also a few places where you can optimize the code

  • Instead of using get_the_category(), use wp_get_post_terms(). It is a bit faster, and you have the option to just get the term ID’s from the post categories. This is one place where you can optimize your code

  • ID is not a valid property of get_the_category(), it should be cat_ID or you can use term_id

  • You can just return $html

  • There is no need to use a shortcode here. It is a bit slower as shortcodes need to be parsed. You can simply call the function where needed.

You can simplify your code to the following

function get_related_category_posts() {

    $cats = wp_get_post_terms( get_queried_object_id(), 'category', array( 'fields' => 'ids' ));
    $html="";

    $posts = get_posts( array( 'numberposts' => 5, 'orderby' => 'rand', 'category__in' => $cats ) );

        if ( $posts ) {
            foreach ( $posts as $post ) {
                $meta = get_post_meta( $post->ID );
                $image = $meta['og_image'][0];
                $html .= '<a href="http://www.abcmysitexyz.com/'.$post->post_name."https://wordpress.stackexchange.com/"><img src="'.$image.'"  class="alignnone"  /></a>';
            }
        }
    return $html; 

}

and then call it like echo get_related_category_posts(); where ever you need it inside your single template

Leave a Comment