List posts related by category in wordpress

Asked

Viewed 122 times

0

When opening a blog post, I need to pick up all posts, ordered by descending date, that have the same label and are in the same state of the open post. This is OK.

I need to filter more, the category needs to be the same as the post too.

$args = array(
    'post_type' => array('post'),
    'post__not_in' => $exclude_items,
    'posts_per_page' => 4,
    'orderby' => 'date',
    'order' => 'DESC',
    'meta_query' => array(
      'relation' => 'AND',
        array(
          'key'     => 'label',
          'value'   => get_field('label'),
          'compare' => 'LIKE',
        ),
        array(
          'key'     => 'estado',
          'value'   => get_field('estado'),
          'compare' => 'LIKE',
        ),
    )
  );

  $related_posts = get_posts( $args );

It must be something like this, but I don’t know if it’s right, but it seems to me that get_the_category() returns an array with all categories.

    'category_name' => get_the_category(),

1 answer

1


I found the answer here: https://enternauta.com.br/wordpress/posts-relacionados-por-categorias-ou-tags-no-wordpress/ actually returns an array, and use category__in in the category ids array.

$categories = get_the_category($post->ID);
if ($categories) {
    $category_ids = array();
    foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;

    $args=array(
        'category__in' => $category_ids,
        'post__not_in' => array($post->ID),
        'showposts'=>6, // Quantidade de itens na lista
        'caller_get_posts'=>1
    );
    $my_query = new wp_query($args);
    if( $my_query->have_posts() ) {
        echo '<h3>Artigos relacionados</h3><ul>';
        while ($my_query->have_posts()) {
            $my_query->the_post();
        ?>
            <li><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
        <?php
        }
        echo '</ul>';
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.