Home > other >  Show post from specific category on the archive page
Show post from specific category on the archive page

Time:03-31

I am using ACF and CPT UI to add my projects. Each projects post have a custom category assigned to it.

I am using this code below to display all projects in the archive page…

<?php $loop = new WP_Query( array( 'post_type' => 'projets', 'paged' => $paged ) );
      if ( $loop->have_posts() ) :
        while ( $loop->have_posts() ) : $loop->the_post(); ?>

          <div >
            <div >
             <a href="<?php the_permalink(); ?>"><h3> <?php the_title(); ?></h3></a>
            </div>
          </div> 

        <?php endwhile;
        if (  $loop->max_num_pages > 1 ) : ?>
          <div id="nav-below" >
            <div ><?php next_posts_link( __( '<span >&larr;</span> Previous', 'domain' ) ); ?></div>
            <div ><?php previous_posts_link( __( 'Next <span >&rarr;</span>', 'domain' ) ); ?></div>
          </div>

        <?php endif;
      endif;
      wp_reset_postdata();?>

The code works well to get all the posts from all category but when I go to projects/category1, it still show all projects.

How can I modify this to show only the projects from specific category ?

CodePudding user response:

this is a good reference for WP_Query

https://developer.wordpress.org/reference/classes/wp_query/

This will show only post from a specific category

replace 'my_category_slug' with the category you are interested in.

<?php $loop = new WP_Query( 
    array( 
        'post_type' => 'projets',
        'paged' => $paged,
        'category_name' => 'my_category_slug'
    ));

      if ( $loop->have_posts() ) :
        while ( $loop->have_posts() ) : $loop->the_post(); ?>

          <div >
            <div >
             <a href="<?php the_permalink(); ?>"><h3> <?php the_title(); ?></h3></a>
            </div>
          </div> 

        <?php endwhile;
        if (  $loop->max_num_pages > 1 ) : ?>
          <div id="nav-below" >
            <div ><?php next_posts_link( __( '<span >&larr;</span> Previous', 'domain' ) ); ?></div>
            <div ><?php previous_posts_link( __( 'Next <span >&rarr;</span>', 'domain' ) ); ?></div>
          </div>

        <?php endif;
      endif;
      wp_reset_postdata();?>

CodePudding user response:

have you tried WP default loop without any custom WP_Query i.e.

<?php if ( have_posts() ) : ?>

because WP automatically determines which category projects post you're trying to view and show the projects post accordingly. 

Right now you're mentioning the "'post_type' => 'projets'" so due to that it's showing all the projects.

so please use WP default loop then view the category i.e.
sitename.com/CPT_taxonomy/category_name

then it'll only show the project related to that category only. 
  • Related