lkl
lkl

Reputation: 263

Wordpress query posts by tag and category

I'm trying to create a set of WP pages with indices to all posts which have tag X as well as category Y.

I found this which seems to do exactly what I want and I understand how to edit it for each index page, but I don't know where/how to use the actual code to create the index pages.

global $wp_query;
    $args = array(
    'category__and' => 'category', 
    'tag__in' => 'post_tag', //must use tag id for this field
    'posts_per_page' => -1); //get all posts

$posts = get_posts($args);
    foreach ($posts as $post) :
//do stuff 
 endforeach;

TIA for your help.

Upvotes: 1

Views: 7635

Answers (2)

lkl
lkl

Reputation: 263

This is what finally worked - note that I needed the category ID but the tag slug.

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

<?php query_posts( 'cat=6&tag=a1&&orderby=title&order=asc' );?>

<?php while ( have_posts() ) : the_post();?>

<?php get_template_part( 'content', 'search' ); ?>

<?php endwhile; ?>

<?php else : ?>

Upvotes: 1

Web Guy
Web Guy

Reputation: 92

You use that code to replace the basic query in the loop in your template.

https://codex.wordpress.org/Function_Reference/query_posts

Upvotes: 0

Related Questions