0

I need to redirect to the first child page in a hierarchical Custom Post Type. For the love of me I have scoured high and low, but all the solutions seem to involve applying a template to the parent that kicks off redirection.

I need to bypass the template and redirect to the first child with a nice, clean bit of code in functions.php. Can someone help?

Thanks!

2
  • It is not clear what you want. A template will be used no matter what. I think maybe you want the template_redirect hook but I have no idea what conditions you need to match.
    – s_ha_dum
    Commented Feb 18, 2013 at 0:46
  • Ok, that was me being silly. Of course it will use a template as per Template Hierarchy. I have installed the redirect code inside the single-{custom-post-type}.php file and it works a treat. Thanks for your patience :-)
    – Jacob
    Commented Feb 18, 2013 at 4:58

1 Answer 1

2

I'm not sure how you define "first child" - alphabetically, by highest or lowest ID, etc., but if you can query for the child you want via WP_Query, then you can filter single_template to do the redirection based on whether the requested post has a parent or not:

function wpa87313_redirect_post_type( $template ){
    // if this isn't the right post type, return
    if( ! is_singular( 'my_post_type' ) )
        return $template;

    // if this post has a parent, return
    global $wp_query;
    if( 0 != $wp_query->post->post_parent )
        return $template;

    // query for the child of this parent
    // here's where you need to sort out what a first child is  
    $child = new WP_Query(
        array(
            'post_parent' => $wp_query->post->ID,
            'post_type'   => 'my_post_type',
            'posts_per_page' => 1,
            // orderby?
            // order?
        )
    );

    // if a child was found, redirect to it
    if( ! empty( $child->posts ) ){
        wp_redirect( get_permalink( $child->post->ID ) );
        exit;
    }

    return $template;
}

add_filter( 'single_template', 'wpa87313_redirect_post_type', 10, 1 );
2
  • Pay attention to the single_template filter. From version 3.4 this filter is deprecated. codex.wordpress.org/Plugin_API/Filter_Reference/single_template Commented Feb 20, 2013 at 5:59
  • well, the bizarre thing is, it's still a valid filter. codex says it's deprecated in favor of {$type}_template, which in the case of single.php, is... single_template.
    – Milo
    Commented Feb 20, 2013 at 6:05

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.