Get category related only to the current single-post

51 Views Asked by At

I'd like to ask for help. I don't know if its possible.

I have a "single-teams.php" custom post type, there I'm using a foreach get_posts loop and I would like to showcase only the related news(posts) category. So if I have "XYZ" single-teams post I would like to showcase posts only with "XYZ" category. If have "XZY" single-teams post I want it to showcase posts only with the "XZY" category.

    $args = array(
    'posts_per_page'   => 4,
    'offset'           => 0,
    'orderby'          => 'date',
    'order'            => 'DESC',
    'category__in'     => array(2),
    'post_type'        => 'post',
    'post_status'      => 'publish',
    'suppress_filters' => true,
);
$news = get_posts( $args );
foreach ( $news as $post ) : 
    setup_postdata( $post ); 
    $image = get_field('image', $post->ID);
    $image = $image['sizes']['large'];
        $catNames = array();
        foreach( (get_the_category()) as $category) {
            $catNames[] = $category->cat_name;
        }

                           

I have this code so far. But it showcases the "XZY" category posts on the "XYZ" single post as well.

1

There are 1 best solutions below

4
Valerio Porporato On BEST ANSWER

It's not clear to me how post-types teams and post are related. What do you mean by

"XYZ" category

The category whose slug is "xyz"? The category whose name is "XYZ"?

UPDATE

Thanks for your clarifications. So you want that, if you are on the "XYZ" team page, the posts assigned to the category whose name is "XYX" are shown? Try using the tax_query argument in the custom query:

$args = array(
    'posts_per_page'   => 4,
    'offset'           => 0,
    'orderby'          => 'date',
    'order'            => 'DESC',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field' => 'name',
            'terms' => get_the_title()
        )
    ),
    'post_type'        => 'post',
    'post_status'      => 'publish',
    'suppress_filters' => true,
);
$news = get_posts( $args );
foreach ( $news as $post ) : 
    setup_postdata( $post ); 
    $image = get_field('image', $post->ID);
    $image = $image['sizes']['large'];
        $catNames = array();
        foreach( (get_the_category()) as $category) {
            $catNames[] = $category->cat_name;
        }
endforeach;