我需要一些关于关键字自定义查询的帮助。
我将关键字发送到我的页面,在那里我想列出那些post\\u title包含我发送的关键字的帖子。
我的问题如下:
$q = \'SELECT guid, post_content, post_title, post_parent, post_type FROM wp_posts WHERE (post_title REGEXP \'".$keyword."\') AND post_type="attachment"\';
如何将其实现到Wordpress中并使其工作?
我见过很多鹬,但我真的很难做到这一点。
我找到了一个看起来不错的代码,但缺少显示部分,请参见问题末尾。
global $wpdb;
// If you use a custom search form
$keyword = sanitize_text_field( $_REQUEST[\'mykey\'] );
// If you use default WordPress search form
// $keyword = get_search_query();
$keyword = "%{$keyword}%";
// 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
endwhile; endif;