Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Search within a category in worpdress

I'm trying to search within a single category on wordpress using the code below

`

    $args = new WP_Query( 'cat=199' );
    if( $args->have_posts() ){

    while ( $args->have_posts() ){ $args->the_post();
        get_template_part('content', 'what-we-eat');

    } ?>

    <?php   

    }
    else{
        _e( 'Sorry, no posts matched your criteria.' );
    }

`

however, the results shows all of the posts within that category even though the search term updates with the search term used.

Any ideas where i'm going wrong?

EDIT

I've noticed then when I remove my custom query it works, but pulls in posts from all of the categories on my blog which is what I don't want. So it's a question of excluding all other categories

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Try this

<?php

global $post;
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 199 );

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <li>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
<?php endforeach; 
?>
over 4 years ago · Santiago Trujillo Report

0

You want standard WP search to work in only one category? Try to add this code to the functions.php of your theme:

function search_rules($query) {
  if ($query->is_search) {
    $query->set('cat','199');
  }
  return $query;
}
add_filter('pre_get_posts','search_rules');
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!