WordPress.org

Forums

Current category within get_posts (2 posts)

  1. yollyflopp
    Member
    Posted 3 years ago #

    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.

  2. racer x
    Member
    Posted 3 years ago #

    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

Topic Closed

This topic has been closed to new replies.

About this Topic