4

How can I make it so when the blog link in the nav bar is clicked it redirects to the most recent post?

I know how to display just the latest post on the blog page, but I want it to actually redirect to the post page itself as I'm displaying a full screen background image called in via a custom metabox on each post page.

Is there perhaps a PHP query and redirect function I can apply to the blog page template, or is there a better way?

UPDATE: the following redirect script works great but I just need a way to get the URL of the latest post:

$URL = "http://www.google.com";
wp_redirect( $URL, 301 ); 
exit; 

1 Answer 1

10

You can use the get_posts() function:

<?php 
/*
Template Name: Redirect
*/

$args = array(
    'posts_per_page' => '1',
    'post_type' => 'post'
);
$post = get_posts($args);
if($post){
    $url = get_permalink($post[0]->ID);
    wp_redirect( $url, 301 ); 
    exit;
}
5
  • thank you but unfortunately i can't get this to work. I have put it in a new template file and then assigned my 'blog' page to use that template - is that correct?
    – fxfuture
    Commented Sep 25, 2011 at 4:36
  • Yes. I'll update my answer. Commented Sep 25, 2011 at 4:43
  • Hi Brian. I'm now trying to do the same thing with categories. Do you happen to know how I can do this? My question is here. Thank you - wordpress.stackexchange.com/questions/29456/…
    – fxfuture
    Commented Sep 26, 2011 at 5:50
  • Hi Brian, this was working fine until I changed my permalink structure. Any ideas why? Thanks
    – fxfuture
    Commented Oct 7, 2011 at 19:30
  • 1
    I might be overthinking things but for this use case is a 301 appropriate? Given that the latest post might change regularly isn't it by definition a temporary redirect? Especially as you may still want Google to index the posts page itself, not the redirect destination. (genuine question, I have no idea) Commented Apr 6, 2017 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.