1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Limit a Wordpress query to a specific category?

Discussion in 'WordPress' started by Kerosene, Dec 18, 2008.

  1. #1
    I use this code to pull in a random post in my WordPress sidebar. The code below works fine, but I'd like to limit it to a specific category id.
    SEMrush
    Any ideas?

    $rand_posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY RAND() LIMIT 1");
    Code (markup):
     
    Kerosene, Dec 18, 2008 IP
    SEMrush
  2. Kerosene

    Kerosene Alpha & Omega™ Staff

    Messages:
    11,363
    Likes Received:
    571
    Best Answers:
    4
    Trophy Points:
    385
    #2
    Found it. Just in case anyone else needs an answer to this...

    $rand_posts = get_posts('numberposts=1&category=4&orderby=rand');
    foreach ($rand_posts as $post) {
    the_title();
    // etc
    }
    PHP:
    EDIT, actually... found an even better way:

    $my_query = new WP_Query('showposts=1&category_name='.$catslug.'&orderby=rand'); 
    while ($my_query->have_posts()) {
    $my_query->the_post();
    the_title();
    // etc
    }
    PHP:
     
    Kerosene, Dec 18, 2008 IP
  3. designz

    designz Peon

    Messages:
    301
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #3
    <?php $my_query = new WP_Query('category_name=Featured&showposts=1'); while ($my_query->have_posts()) : $my_query->the_post(); ?>
    
    Code (markup):
    I use that above code. It displays 1 post in the category with the name Featured (This is the actual category name not slug)


    Aslo if you have mutiple loops

    <?php if (have_posts()) : while (have_posts('category_name=News&showposts=10')) : the_post();if( $post->ID == $do_not_duplicate ) continue; update_post_caches($posts); ?>
    Code (markup):
     
    designz, Dec 18, 2008 IP