Search code examples
wordpressposts

Make a specific post category show in wordpress


I am trying to run a loop that queries only a specific category from my wordpress. this is what i have but it shows all of my post instead of just my post under the category of 'testimonials'

    <div class="row">
          <?php if (is_page()) {
            $cat=get_cat_ID($post->post_title); //use page title to get a category ID
            $posts = get_posts ('cat=$cat&showposts=5');
            if ($posts) {
              foreach ($posts as $post):
                setup_postdata($post); ?>

                  <div class="col-sm-12">
                    <div class="box" data-toggle="modal" data-target="#myModal1">
                      <h1><?php the_title(); ?></h1>
                      <?php the_content(); ?>
                    </div>
                  </div>

              <?php endforeach;
            }
          }?>
      </div>

Please any help would be great, thnx


Solution

  • Thats because the arguments sent to get_posts isnt correct. Try:

    $posts = get_posts(array(
        'category'=>$cat,
        'posts_per_page'=>5, //This changes how many posts are returned
        'offset' => 0, //This changes where it search starts from
    );
    

    Have a look at the documentation here

    There is also a better way to get the post category:

    $cat = get_the_category();
    

    You dont have to pass the post ID to it because it will default to the current $post->ID. You can checkout that documentation here

    Its also probably a bad idea to use $post in your foreach loop as that will overwrite the global $post variable. You may want to use something like $curPost