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');