0

I see wordpress gives you opportunity for searching posts with exactly N categories...so i tried by myself and produced this code...

$catIDs = get_cat_ID( $cat_name='CategoryName1' );
$catIDs .= ',' . get_cat_ID( $cat_name='CategoryName2');
$catIDs .= ',' . get_cat_ID( $cat_name='CategoryName3');
echo "$catIDs </br>";

$my_query = new WP_Query( array( 'category__and' => array($catIDs) ) );
if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post(); ?>
<li>
    <a href="<?php the_permalink(); ?>"> <?php the_ID(); ?> </a>
</li>
<?php endwhile; endif; wp_reset_postdata(); ?>

if i replace the array($catIDs) with 1,2,3 (the ID of the category) this solution works....why with the variable $catIDs it doesn't? and how can i make this solution dynamic (i have a form and i would pass the data in this form -category name/ID in this case)

0

Make sure you are providing correct category names into the function get_cat_ID().

<?php 
$catIDs = array();
$catIDs[] = get_cat_ID( 'CategoryName1' );
$catIDs[] = get_cat_ID( 'CategoryName2' );
$catIDs[] = get_cat_ID( 'CategoryName3' );

$my_query = new WP_Query( 
    array( 
        'category__and' => $catIDs 
    ) 
);
if( $my_query->have_posts() ) : 
    while( $my_query->have_posts() ) : $my_query->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"> <?php the_ID(); ?> </a>
        </li> <?php 
    endwhile; 
endif; 
wp_reset_postdata(); 
?>
  • Missed the part 'making this dynamic': You need to create a array out of form submitted category ids/ category names and do the same as above. – Subharanjan Dec 10 '13 at 11:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.