WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Display just the first sticky post, if none return the last post published (5 posts)

  1. lerizzle
    Member
    Posted 2 years ago #

    The above line is found in all the docs but doesn't work for me.

    I'm trying to get the 1 sticky post within a Category and if not just return the latest. If there's no sticky, nothing is returned.

    $args = array( 'category' => 6, 'posts_per_page' => 1, 'post__in'  => get_option( 'sticky_posts' ), 'ignore_sticky_posts' => 1);
    $myposts = get_posts( $args );

    Help please

  2. vtxyzzy
    Member
    Posted 2 years ago #

    It isn't clear if you want the latest post in category 6, or the overall latest post. For the latest post in cat 6, try this:

    $args = array( 'category' => 6, 'posts_per_page' => 1, 'post__in'  => get_option( 'sticky_posts' ), 'ignore_sticky_posts' => 1);
    $myposts = get_posts( $args );
    if (!$myposts) {
       $args = array( 'category' => 6, 'posts_per_page' => 1,  'ignore_sticky_posts' => 1);
       $myposts = get_posts( $args );
    }

    If you want the latest of all posts, take out the category argument.

  3. lerizzle
    Member
    Posted 2 years ago #

    Thanks that's what I ended up doing, 2 queries.

    I want the sticky in category 6, if there's none get the latest in category 6.

  4. vtxyzzy
    Member
    Posted 2 years ago #

    If you have solved the problem, please use the dropdown on the right to mark the topic 'Resolved'.

  5. YFR
    Member
    Posted 1 year ago #

    This is old and solved but I just had the same problem like lerizzle. Maybe this helps someone. Was on my dev install.

    In my case i had to delete an old sticky option in wp_options database table. There was an old post marked sticky that did not exists anymore.

    get_option( 'sticky_posts' ) found an post_id that does not exists anymore and tried to display this one.

Topic Closed

This topic has been closed to new replies.

About this Topic