I hope someone can help me, I have been trying to find a solution to this for a long time now.
I am creating a kind of Branch finder on a site whereby the user needs to enter their UK Postcode, a search is then performed on the title of a Custom Post Type (postcode). If there is a match the user needs to be redirected to the Custom Post Type Single Entry. If not the user needs to be redirected to a "No branch found" page.
The problem I am having is the format of the postcode search. For example within the Custom Post Type postcodes (the title) are stored as the first part of a UK Postcode - RG1, RG2, RG12, RG42, etc.
On the front end a user may enter postcodes in either of these formats:
- RG5
- RG54PZ
- RG5 4PZ
- RG42
- RG423XF
- RG42 3XF
I need a way for WordPress to still perform the search and redirect to the correct single entry.
I have a function within my function.php file which looks like this:
function SearchPostcode($query) {
if ($query->is_search) {
$s = isset( $_REQUEST['s'] ) ? sanitize_text_field( $_REQUEST['s'] ) : '';
$s = explode( ' ', $s );
if ( count( $s ) > 1 ) {
$s = $s[0];
}
$query->set('post_type',array('postcode'));
$query->set('s',$s);
}
return $query;
}
add_filter('pre_get_posts','SearchPostcode');
I also have a search.php page which looks like this:
<?php
if( !empty( $posts ) ) : ?>
<?php // the loop ?>
<?php foreach ( $posts as $post ): setup_postdata( $post ); ?>
<?php // redirect to the post (postcode)
wp_redirect( get_permalink( $post->ID ) ); exit;
?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
No Branch Found
<?php endif; ?>
I'd appreciate any help.
Thanks.
Aucun commentaire:
Enregistrer un commentaire