I am trying to redirect the category link to the first child post. I am using following code in category.php. This redirects, but link doesn't go to first child post. How can I redirect to the first child post, in ASC order by date?

 Category Template:
 Template URI: 
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        wp_redirect( get_permalink( $post->ID ) );

You are much too late in the page load sequence to redirect. You need to redirect before headers are sent to the browser. The template_redirect hook should be a pretty good option:

function redirect_cat_wpse_207298() {
  if (is_category()) {
    global $post;
  • hi, this doesn't work. – Levent Kökdemir Nov 1 '15 at 21:29
  • Where did you put the code? It works fine when I test it. – s_ha_dum Nov 1 '15 at 21:30
  • sorry, I mistakenly added this to category.php, in functions.php working but this goes to newest child post not the oldest first post? how can I do that in ASC order? – Levent Kökdemir Nov 3 '15 at 21:10
  • To get the oldest you would need to use pre_get_posts to change the order argument for the archive. – s_ha_dum Nov 4 '15 at 4:14

You could probably use get_posts() to refine what you are looking for/where you want to be redirected.

See the Codex for the general use of get_posts() and its parameters and you could use this (untested, hope it works) for your redirect:

$args = array('posts_per_page' => 1);
$postslist = get_posts($args);
foreach ($postslist as $post) :
  • Hi, thanks for reply, I've tested this, but doesn't work. – Levent Kökdemir Nov 1 '15 at 21:22
  • What does not work? – flomei Nov 2 '15 at 0:38
  • I've added this to category.php but not redirecting? – Levent Kökdemir Nov 3 '15 at 21:11
  • Ah, have a look at what @s_ha_dum wrote above. Your <code>category.php</code> runs too late, the redirect needs to be made much earlier. You could probably combine my code with his, for ordering and getting the first post... – flomei Nov 5 '15 at 12:43

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.