0

I'd like to modify the code below so it grabs the data based on the category the post is in and 'only' that category, not children categories, not other categories, only the category of the current post.

I reviewed the instructions get_the_category() and WP_Query Category Parameters, but I'm doing something wrong.

Any suggestion to tweak this?

My category structure is as follows.

ParentA
-childA
-childB
--childB1
--childB2
-childC

ParentA acts as a 'container', there are no posts in it. I'd like posts in category -childA to display data from other posts in -childA and 'only' from -childA, nothing else.

The code below was contributed by Andrei Gheorghiu (thanks again)

 /**
     * tag related posts
     */
    function relatedCategoryPosts() {
$cats = get_the_category();
$html = '';
if ( $cats ) {
    $cat_ids = array();
    foreach ( $cats as $cat ) {
        $cat_ids[] = $cat->ID;
    }
    $posts = get_posts('numberposts=5&orderby=rand&fields=all&category__in='.implode(',',$cat_ids));

    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.'/"><img src="'.$image.'"  class="alignnone"  /></a>';
        }
    }
}
return do_shortcode($html);     
}

add_shortcode('related', 'relatedCategoryPosts');
3

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.'/"><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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.