WordPress.org

Ready to get started?Download WordPress

Forums

Linking to posts in two categories (both -- e.g. humor + videos) (2 posts)

  1. righter
    Member
    Posted 4 years ago #

    Hi there,

    I'd like to create a link that returns a page displaying posts in 2 (or more) categories. By 2 categories, I mean posts in both categories (not posts in either). (For example, a post with a funny video might be categorized "humor" and "videos," so it would be returned by this query, but a post that was only categorized "video" would not.)

    N.B.: I've already read the forum posts with code snippets that address issues very closely related to this (here, here, and here). These do not answer my question enough for me to move forward.

    In the Codex, it says that to show posts in category 2 and 6, do:
    query_posts(array('category__and' => array(2,6)));

    This is exactly what I need to do, but I need a little help with the implementation, and I'm a little rusty on WordPress after a bit of a hiatus. In that first forum post I linked, here is the suggested code:

    <?php
    
    //The Query
    query_posts(array('category__and' => array(8,387)));
    
    //The Loop
    if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    
            <li><a href="<?php the_permalink(); ?>">
              <?php the_title(); ?>
              </a>  </li>
     <?php endwhile; else: ?>
     <?php endif; ?>

    What do I do with this? Do I copy a page from my template (like index.php) and then replace something in the Loop with this instead? Any implementation help would be greatly appreciated, as I'm not sure how to begin.

    Thanks for reading this far!

    (When I first thought of this, I thought it would be as simple as mysite.com/category/humor+video -- ha.)

  2. esmi
    Forum Moderator
    Posted 4 years ago #

    I'd suggest creating a custom page template based on your page.php file and then adding:

    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args= array(
    	'category__and' => array(8,387),
    	'paged' => $paged
    );
    query_posts($args);
    ?>

    just before the start of the Loop.

Topic Closed

This topic has been closed to new replies.

About this Topic