Eko UK Limited

How to search by custom meta keys in WordPress

A couple of sites we've been developing recently have required us to create custom post types with meta keys, and then create a search of the values stored in the meta keys. Here's how we achieved it. The code used in this example was written for use with the plugin Job Manager, allowing you to search on vacancies.

Create a custom search form

The first step is to create your own custom search form to bypass the standard wordpress search. This function goes into function.php and then can be called by whatever page you want the form to appear on.

function custom_search_form(){
?>

    

Create your results page

Next you need to create the page that will process the submission of the form, and display the search results.

$region = $_GET['region'];
$salary = $_GET['salary'];
$description = $_GET['description'];
$searched_posts = meta_key_search($region, $salary, $description);
while($searched_posts->have_posts()) : $searched_posts->the_post();
   jobman_display_job_search($post->ID);
endwhile;
This gets the search terms passed into the page via the URL, and then uses two functions to process them. The first function performs the search query, the second works with search results and outputs them in a useful way.

The search function

Add this to functions.php

function meta_key_search($region, $salary, $description){
global $wpdb;
$args = array(
          'post_type' => 'jobman_job',
          'orderby' => 'meta_value_num',
          'order' => 'ASC',
          'meta_query' => array(
               array(
                  //data4 is location 
                  'key' => 'data4',
                  'value' => $region,
                  'compare' => 'LIKE',
                ),
               array(
                  //data1 is salary
                  'key' => 'data1',
                  'value' => array($salary, 99999999),
                  'compare' => 'BETWEEN',
               ),
               array(
                  //data5 is description
                  'key' => 'data5',
                  'value' => $description,
                  'compare' => 'LIKE',
               )
           ),
          'sentance' => true, 
           );

$searched_posts = new WP_Query($args);

echo "
Total results: "; echo $total_results = $searched_posts->found_posts; echo "

"; return $searched_posts; }
The 'post_type' is the name of your custom post type, for Job Manager this is 'jobman_job'. The Meta Query is where the search on meta values happens. Use the meta key, the value you're looking for, and how you want to compare the query with the stored data. The final line 'sentance'=>true, allows the query to search for phrases in the database. Without this line it will only search for exact matches. Sentance isn't a typo (by me anyway), it's in the core wordpress code.

Processing the results

This code is probably more complicated than most custom post types will need because it's been built to work with the existing Job Manager plugin. If all you want to do is list the post title in your results you don't even need this function. This is for putting content from the meta keys into the results page.
function jobman_display_job_search($job) {

global $jobman_shortcode_job, $jobman_shortcodes, $jobman_field_shortcodes;
$options = get_option( 'jobman_options' );
$content = '';

if( is_string( $job ) || is_int( $job ) ) 
    $job = get_post( $job );

if( $options['user_registration'] && $options['loginform_job'] )
    $content .= jobman_display_login();

if( NULL != $job ) {
     $jobmeta = get_post_custom( $job->ID );
     $jobdata = array();
     foreach( $jobmeta as $key =>; $value ) {
         if( is_array( $value ) ) 
             $jobdata[$key] = $value[0];
         else 
             $jobdata[$key] = $value;
      }
}

// Check that the job hasn't expired
if( array_key_exists( 'displayenddate', $jobdata ) && '' != $jobdata['displayenddate'] && strtotime($jobdata['displayenddate']) <= time() )
    $job = NULL;

// Check that the job isn't in the future
if( strtotime( $job->post_date ) > time() )
    $job = NULL;

if( NULL == $job ) {
    $page = get_post( $options['main_page'] );  
    $page->post_type = 'jobman_job';
    $page->post_title = __( 'This job doesn't exist', 'jobman' );

    $content .= '

' . sprintf( __( 'Perhaps you followed an out-of-date link? Please check out the jobs we have currently available.', 'jobman' ), get_page_link( $options['main_page'] ) ) . '

'; $page->post_content = $content; return array( $page ); } $template = $options['templates']['job_list']; jobman_add_shortcodes( $jobman_shortcodes ); jobman_add_field_shortcodes( $jobman_field_shortcodes ); $jobman_shortcode_job = $job; $content .= do_shortcode( $template ); jobman_remove_shortcodes( array_merge( $jobman_shortcodes, $jobman_field_shortcodes ) ); $page = $job; $page->post_title = $options['text']['job_title_prefix'] . $job->post_title; $page->post_content = $content; echo $page->post_content; return array( $page ); }
This retrieves the meta keys and then uses the existing job list template to show the results. If you are not using Job Manager, this is the part of the function that should help you to retrieve the meta values.
$jobmeta = get_post_custom( $job->ID );

$jobdata = array();
foreach( $jobmeta as $key => $value ) {
    if( is_array( $value ) ){
        $jobdata[$key] = $value[0];
    } else {
        $jobdata[$key] = $value;
    }
}
zp8497586rq

Comments are closed.

Scroll to Top