0

I've been searching around for a few hours now and can't figure out how to do this. Seems really simple. I've seen lots of redundant examples on how to redirect to a single post when a search result returns only one post, but what if I set up a custom WP_query to only show posts by a custom field/metabox value and if there is only one post with that value--redirect to that post? So far I have a custom WP_Query set up on a page template which does what I want it do but I can't figure out the conditional redirect part:

<?php
$rawfiltertag = get_post_meta($post->ID, '_cmb_client_name', true);
$filtertag = sanitize_title( $rawfiltertag );
// WP_Query arguments
$args = array (
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => '_cmb_client_target',
            'value' => $rawfiltertag
        )
    )
);
// The Query
$the_query = new WP_Query( $args );
if ($the_query->post_count == 1) {
    wp_redirect( get_permalink( $the_query->posts['0']->ID ) );
}   
?>

Right now this does nothing on the page I am trying to set it up on.

1

2 Answers 2

1

You can do this by checking the number of results returned by your query. Try this.

<?php

    $rawfiltertag = get_post_meta( $post->ID, '_cmb_client_name', true );
    $filtertag = sanitize_title( $rawfiltertag );

    // wp_query arguments
    $args = array (
        'post_type' => 'post',
        'meta_query' => array(
            array(
                'key' => '_cmb_client_target',
                'value' => $rawfiltertag
            )
        )
    );

    // the query
    $the_query = new WP_Query( $args );

    if ( $the_query->post_count == 1 && $the_query->max_num_pages == 1 ) {
        wp_redirect( get_permalink( $the_query->posts['0']->ID ) );
        exit;
    }

?>
0

I think you only have to change '0', that is a string, by simply 0, that is a integer corresponding to the first place of the array of posts.

I thik this is a good idea, maybe WordPress should do it by default ^^

Your Answer

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

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