Forums

[resolved] Need to display ONLY the category of the current top post (6 posts)

  1. CHUDSF
    Member
    Posted 5 years ago #

    On the index page of the blog, I would like to ONLY display the category of the most recent post. So if I post category 6, it should only display posts of that category. If I then do a post of category 3, it would no longer show category 6, only category 3. And so on...

    Basically the blog will have a rotating identity on the index page (I have a different header image for each category too), and this will keep older/different category posts from showing up there.

    Anyone know a way to do this? Asked a month ago, thought I'd try again.

  2. Kafkaesqui
    Moderator
    Posted 5 years ago #

    Hmm. I guess you could perform a quick SQL query for it:

    <?php $latest_cat = $wpdb->get_var("SELECT category_id FROM $wpdb->posts LEFT JOIN $wpdb->post2cat ON ID = post_id WHERE post_status = 'publish' ORDER BY post_date DESC LIMIT 1"); ?>

    Then use query_posts() to initialize The Loop in your template, passing $latest_cat for the value of 'cat':

    <?php query_posts("cat=$latest_cat"); ?>

  3. CHUDSF
    Member
    Posted 5 years ago #

    I will give this a shot, thank you so much!

  4. CHUDSF
    Member
    Posted 5 years ago #

    This worked swimmingly with one exception -- If I schedule posts in advance it grabs the $latest_cat value from those (instead of the current, displayed post). Anyone care to suggest a way to filter it so it only grabs the latest LIVE post?

  5. Kafkaesqui
    Moderator
    Posted 5 years ago #

    Change the query to:

    <?php
    $now = current_time('mysql');
    $latest_cat = $wpdb->get_var("SELECT category_id FROM $wpdb->posts LEFT JOIN $wpdb->post2cat ON ID = post_id WHERE post_status = 'publish' AND post_date <= '$now' ORDER BY post_date DESC LIMIT 1");
    ?>

    For WordPress 2.1, this should do:

    <?php
    $latest_cat = $wpdb->get_var("SELECT category_id FROM $wpdb->posts LEFT JOIN $wpdb->post2cat ON ID = post_id WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC LIMIT 1");
    ?>

  6. CHUDSF
    Member
    Posted 5 years ago #

    Excellent. Thanks so much, Kafkaesqui, your assistance is much appreciated.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags