• Hi,

    I am using some code to retrieve the current page’s category so that the sidebar displays all of the other posts from said category.

    I have tested that my $catid retrieves the correct category id, and the HTML code posts fine when given an exact category id (i.e. 5). It is just when using a variable in the parameter of get_posts() that it does not seem to work.

    Here is my current code:

    <?php
    if (is_category() || is_single()) { 
    
    foreach((get_the_category()) as $cat) {
    	$catid = $cat->cat_ID;
    	$catname = $cat->cat_name;
    }
    $sidebarparam = 'numberposts=10&category=$catid';
    ?>
    <ul>
       <?php
          $catposts = get_posts($sidebarparam);
          foreach($catposts as $post) :
       ?>
       <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
       <?php endforeach; ?>
    </ul>
    } ?>

    Any help would be appreciated!

Viewing 3 replies - 1 through 3 (of 3 total)
  • You need to use double-quotes in order to interpolate a variable into a string:

    $sidebarparam = "numberposts=10&category=$catid";

    try either:

    $sidebarparam = 'numberposts=10&category=' . $catid;

    or:

    $sidebarparam = "numberposts=10&category=$catid";

    this has to do with the way php deals with variables within strings.

    Thread Starter ericjohnson

    (@ericjohnson)

    Of course! I always forget about the string interpolation rules!

    Thanks guys

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Unable to pass current category ID in paramter’ is closed to new replies.