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.