WordPress.org

Support

Support » How-To and Troubleshooting » Current category within get_posts

Current category within get_posts

  • I’m trying to show the posts from only the category I’m in at the time, now my code looks like this:

    <?php
    global $post;
    $myposts = get_posts( $args );
    foreach( $myposts as $post ) :	setup_postdata($post); ?>
    <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
    <?php endforeach; ?>

    But that show all the posts within all categories. I just want to show the ones in the current category, without pointing at a specific category ID, because I have a lot of categories.

Viewing 1 replies (of 1 total)
  • So are you trying to list other posts in the same category on a single post view?

    What are the $args you are using?

    Make sure you are using the best query method.

    Here is one basic example:

    <?php
    $category = get_the_category( get_the_ID() ); // this gets the category array of objects
    $cat_id = $category[0]->cat_ID // remember there could be more than 1 category so this is only the first returned value
    $args = array( 'cat' => $cat_id );
    $myposts = get_posts( $args );
    // continue on ...
    ?>

    There are lots of other solutions here in the forums to achieve this.

    http://codex.wordpress.org/Function_Reference/get_the_category

Viewing 1 replies (of 1 total)
  • The topic ‘Current category within get_posts’ is closed to new replies.