user1845661
user1845661

Reputation: 127

how to query_posts by category slug

I am using the following code to list some pages on my wordpress site:

$args = array( 'posts_per_page' => 12, 'order'=> 'ASC', 'post_type' => 'tcp_product', 'paged' => $paged);
?>
  <?php query_posts($args); ?>
  <?php while (have_posts()) : the_post(); ?>
  <a href="<?php the_permalink(); ?>" id="prod-link">
  <?php if( has_sub_field('images') ): ?>
  <?php $img = get_sub_field('image') ?>
  <img src="<?php echo $img['sizes']['product-index-pic'] ?>" />
  <?php endif; ?>
  </a>
  <?php endwhile; ?>
  <!-- #posts -->
  <div class="pagination">
    <?php posts_nav_link( ' ', '<img src="' . get_bloginfo('template_url') . '/assets/images/prev.jpg" />', '<img src="' . get_bloginfo('template_url') . '/assets/images/next.jpg" />' ); ?>
  </div>
  <!-- .pagination --> 

I am wondering if there would be a way to limit those based on a certain category slug? Thanks in advance

Upvotes: 7

Views: 36982

Answers (2)

Jean
Jean

Reputation: 159

You can use the variable category_name like this:

$args = array( 'category_name' => ***YOUR CATEGORY SLUG***, 'posts_per_page' => 12, 'order'=> 'ASC', 'post_type' => 'tcp_product', 'paged' => $paged);

Upvotes: 16

Adnan
Adnan

Reputation: 579

tax_query is used to get the posts associated with certain taxonomy.

  • {tax} (string) - use taxonomy slug. Deprecated as of Version 3.1 in favor of 'tax_query'.
  • tax_query (array) - use taxonomy parameters (available with Version 3.1).
    • taxonomy (string) - Taxonomy.
    • field (string) - Select taxonomy term by ('id' or 'slug')
    • terms (int/string/array) - Taxonomy term(s).
    • include_children (boolean) - Whether or not to include children for hierarchical taxonomies. Defaults to true.
    • operator (string) - Operator to test. Possible values are 'IN', 'NOT IN', 'AND'.
$args = array(
    'post_type' => 'tcp_product',
    'posts_per_page' => 12,
    'tax_query' => array(
        array(
            'taxonomy' => 'tcp_product_taxonomy',
            'field' => 'slug',
            'terms' => 'your-cat-slug'
        )
     )
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post;
        // do something
    }
}

Upvotes: 15

Related Questions