WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to pass a variable to query_posts (3 posts)

  1. edd_lasthours
    Member
    Posted 4 years ago #

    Hi,

    Sorry, I've been reading http://codex.wordpress.org/Template_Tags/query_posts and trying to work out how to pass a variable I want into the query post, but not been getting very far with it.

    In plain english I'm wanting wordpress to produce a list, in the sidebar, of the 5 most recent posts from category 'x' if the single post someone is looking at is in category 'x'

    The code I came up with that is wrong looks like this:

    <?php
    $category = get_the_category();
    $class=$category[1]->cat_name;
    ?><?php $temp_query = clone($wp_query); ?>
    <?php query_posts('cat=' . $class. '&showposts=5'); ?>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title() ?></a></li>
    <?php endwhile; endif; ?>
    <?php $wp_query = clone($temp_query); ?>

    It's returning the 5 most recent posts of the site.

    Any help would be greatly appreciated!!
    thanks,
    edd

  2. MichaelH
    Member
    Posted 4 years ago #

    From my notes: in a sidebar, if single post, for the first category of that post, display 5 posts in that category, excluding the single post

    <?php
    if ( is_single() ) {
      $cats = wp_get_post_categories($post->ID);
        if ($cats) {
        $first_cat = $cats[0];
        $args=array(
          'cat' => $first_cat, //cat__not_in wouldn't work
          'post__not_in' => array($post->ID),
          'showposts'=>5,
          'caller_get_posts'=>1
        );
        $my_query = new WP_Query($args);
        if( $my_query->have_posts() ) {
          echo 'Related Posts';
          while ($my_query->have_posts()) : $my_query->the_post(); ?>
            <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
           <?php
          endwhile;
        } //if ($my_query)
      } //if ($cats)
      wp_reset_query();  // Restore global post data stomped by the_post().
    } //if (is_single())
    ?>

    also
    http://wordpress.org/search/category+single+sidebar?forums=1
    http://wordpress.org/support/topic/257858?replies=4
    http://wordpress.org/support/topic/179138?replies=4
    http://wordpress.org/support/topic/252228

  3. edd_lasthours
    Member
    Posted 4 years ago #

    Michael, thanks so much for that. And also for showing me how to exclude the single post. Thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic