• Skip to primary navigation
  • Skip to main content
  • Skip to footer

JH Tech Services

A knowledgebase

  • Portfolio
  • Knowledgebase
  • About

Redirect WordPress page to most recent post page

December 7, 2017 by jer0dh

Hello to Mike, my most avid reader.

Had an interesting task. They wanted a page to go to the post page of the most recent post. I thought easy, peasy, but when I got into the details of it, it was harder than I thought. It was a few weeks ago which is ancient history for me so I don’t remember all the details. Pagination was definitely an issue and running a new query and redirecting to the single.php file didn’t work. Ended up with this solution or maybe it’s a work around:

First created page-episodes.php and then created an empty page with the slug, episodes In that php file I put the following code:


$pipe_query = get_posts(array(
    'post_type'         => 'post',
    'posts_per_page'    => 1,
    'meta_key'          => 'episode_date',
    'orderby'           => 'meta_value',
    'order'             => 'DESC',
    'tax_query'         => array(
        array(
            'taxonomy'  => 'post_format',
            'field'     =>  'slug',
            'terms'     =>  array( 'post-format-audio' )
        )
    )
));
if(count($pipe_query) > 0) {

    $wp_query = new WP_Query( array(
        'post_id'        => $pipe_query[0]->ID,  // Using first post of query which is most recent
        'post_type'      => 'post',
        'posts_per_page' => 1

    ) );

    $host = $_SERVER['HTTP_HOST'];

    header("Location: https://$host?p=" . $pipe_query[0]->ID);
}
  • Knowledgebase

Footer

  • Portfolio
  • Knowledgebase
  • About

© 2022