WordPress.org

Ready to get started?Download WordPress

Forums

Expire posts from homepage, but remain published in the archive (3 posts)

  1. robgolbeck
    Member
    Posted 1 year ago #

    I need to show recent news (i.e. posts) on the sidebar of the homepage on a client's site. There can be several weeks between new posts though (it's not a super active industry), so I want the post to expire from the homepage after a set amount of time, but still remain on the News (blog) page.

    One solution I'm thinking about is to create a tag ("featured" or something like that), then show only posts with that tag on the homepage. Then, after a set amount of time, edit the post to remove the tag to remove it from the homepage.

    However, I would prefer to make it expire from the homepage automatically. I'd also like the "Recent News" heading to disappear if there are no posts to display.

    I found a tutorial of how to expire posts with custom fields (e.g. basically, create a custom field with a key of "expiration" and a value of date/time with the format mm/dd/yyyy 00:00:00), but this is too technical for the client. I'd rather set the expiration right in the loop so they don't have to do anything but publish the post.

    Any ideas?

  2. essaysnark
    Member
    Posted 1 year ago #

  3. robgolbeck
    Member
    Posted 1 year ago #

    I figured it out, with some help from the codex and this thread.

    Here's what I went with:

    <?php
         function filter_where($where = '') {
         //only show posts published within the last 30 days
         $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
         return $where;
         }
         add_filter('posts_where', 'filter_where');
    
         // Query posts
         query_posts( 'posts_per_page=1' );
    
         // The Loop
         if (have_posts()) : while ( have_posts() ) : the_post();
         echo '<li>';
         echo '<a href="';
         the_permalink();
         echo '">';
         the_title();
         echo '</a>';
         echo '</li>';
         endwhile; endif;
    
         //remove the filter
         remove_filter('posts_where', 'filter_where');
    
         // Reset Query
         wp_reset_query();
    ?>

    I'm not certain if remove_filter is in the best spot, but it works! :)

Topic Closed

This topic has been closed to new replies.

About this Topic