Skip to content

Instantly share code, notes, and snippets.

@WenLiangTseng
Created July 23, 2013 09:11
Show Gist options
  • Save WenLiangTseng/6061046 to your computer and use it in GitHub Desktop.
Save WenLiangTseng/6061046 to your computer and use it in GitHub Desktop.
Wordpress 搜尋自訂欄位(custom field)的函數
<?php
/*
Source: http://www.deluxeblogtips.com/2012/04/search-all-custom-fields.html
*/
global $wpdb;
// If you use a custom search form
// $keyword = sanitize_text_field( $_POST['keyword'] );
// If you use default WordPress search form
$keyword = get_search_query();
$keyword = '%' . like_escape( $keyword ) . '%'; // Thanks Manny Fleurmond
// Search in all custom fields
$post_ids_meta = $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT post_id FROM {$wpdb->postmeta}
WHERE meta_value LIKE '%s'
", $keyword ) );
// Search in post_title and post_content
$post_ids_post = $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT ID FROM {$wpdb->posts}
WHERE post_title LIKE '%s'
OR post_content LIKE '%s'
", $keyword, $keyword ) );
$post_ids = array_merge( $post_ids_meta, $post_ids_post );
// Query arguments
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'post__in' => $post_ids,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ): while ( $query->have_posts() ) : $query->the_post();
// Do loop here
echo "test";
endwhile;
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment