3

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; 
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
    Sep 25 '11 at 4:36
  • Yes. I'll update my answer. Sep 25 '11 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
    Sep 26 '11 at 5:50
  • Hi Brian, this was working fine until I changed my permalink structure. Any ideas why? Thanks
    – fxfuture
    Oct 7 '11 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) Apr 6 '17 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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