Site logo

Archived topic

How to filter a search results by category and/or tag

5 replies · Started by eduard sans on January 5, 2019

Viewing posts 1–6 of 6

Hi! I would like to know how to filter the search results of a related posts module I have introduced in the file single.php. Right now it always display the same posts (which I assume are the last posts I submitted). Considering the code below, I would like to be able to do two things (separately in different modules):

1) A related posts that shows posts filtered by the category or tag I write down.

2) A related posts module that shows posts randomly (no matter what category or tag).

Any ideas? Thanks in advance!

<div class="relatedposts full-width">
<h3>También te puede interesar...</h3>
<div class="posts-container">
    <?php
  $orig_post = $post;
  global $post;
  $tags = wp_get_post_tags($post->ID);

  if ($tags) {
  $tag_ids = array();
  foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
  $args=array(
  'tag__in' => $tag_ids,
  'post__not_in' => array($post->ID),
  'posts_per_page'=>4, // Number of related posts to display.
  'caller_get_posts'=>1
  );

  $my_query = new wp_query( $args );

  while( $my_query->have_posts() ) {
  $my_query->the_post();
  ?>

  <div class="relatedthumb">
      <div class="relatedimg">
    <a rel="external" href="<? the_permalink()?>"><?php the_post_thumbnail(array(250,200)); ?></a>
    </div>
      <div class="related-title-box">
    <a class="related-title" href="<? the_permalink()?>"><?php the_title(); ?>
    </a>
    </div>
  </div>

  <? }
  }
  $post = $orig_post;
  wp_reset_query();
  ?>

</div>
    </div>  

                    <div class="comments-area">
                        <?php comments_template(); ?>
                    </div>

                    <?php
                endif;

            endwhile;

            /**
             * generate_after_main_content hook.
             *
             * @since 0.1
             */
            do_action( 'generate_after_main_content' );
            ?>
        </main><!-- #main -->
    </div><!-- #primary -->

    <?php
    /**

Hi there,

You could try replacing your args with this:

$args=array(
    'tag__in' => $tag_ids,
    'post__not_in' => array($post->ID),
    'posts_per_page'=>4, // Number of related posts to display.
    'caller_get_posts'=>1,
    'orderby' => 'rand'
);

thanks tom! that works for random posts! but I would like to know also how to display random posts of a certain category or tag, under what line can i write down the category or tag that I want it to display?

Thanks again Tom! and thanks for the link to the wordpress codex. I didn't even know there was such a useful page, definitely going to read it.

You're welcome :)

This archived topic is closed to new replies.