首页 > 解决方案 > WordPress 元查询

问题描述

我正在尝试从数据库中获取带有post_titlelike的帖子%Weapon%

我尝试了下面的代码,但single.php死了。

            $args = array(
                'numberposts'  => 20,
                'category'     => 4,
                'meta_query' => array(
                    array(
                    'key' => 'title',
                    'value' => "Weapon",
                    'compare' => 'LIKE'
                    )
                )
            );
            // $posts = get_posts($args);

            query_posts( $args );

我想从post_title类似的数据库中获取帖子%Weapon%

标签: phpwordpress

解决方案


如果使用“s”=>“Weapon”,它将为您提供标题和内容包含“Weapon”的所有帖子。

但是,如果您只想获得“类似标题”的帖子,则需要在此处添加一些 SQL。

$string="Weapon";
global $wpdb;
$theneededposts=$wpdb->get_col("SELECT ID FROM $wpdb->posts 
  WHERE post_title
  LIKE '%".esc_sql($string)."%' "
);
if (empty($theneededposts)) $theneededposts=array();
$args = array(
           'numberposts'  => 20,
            'category'     => 4,
            'post__in'=>$theneededposts,
           );
$posts = get_posts($args);

推荐阅读