Wordpres元查询喜欢

时间:2019-05-15 12:46:11

标签: php wordpress

我正试图从数据库中获得一个帖子,帖子的位置类似于“%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%”的数据库中获取帖子。

3 个答案:

答案 0 :(得分:0)

问题在于帖子标题不是元值。正如Artem所建议的,看看这个问题,特别是Tomás(有效,但也将搜索帖子内容)和Bullyen(使用自定义查询,仅在标题中搜索)的答案:WordPress get_posts by title like

答案 1 :(得分:0)

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

但是,如果您只想获得“标题一样”的帖子,则需要在其中添加一些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);

答案 2 :(得分:0)

希望下面的代码对您有所帮助

<?php 
    global $wpdb;
    $title = 'Weapon';
    $myposts = $wpdb->get_col( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_status = 'publish' AND  post_title LIKE '%s'", '%'. $wpdb->esc_like( $title ) .'%'  ) );

    foreach ( $myposts as $mypost ) 
    {
        $post = get_post( $mypost );
        //run your output code here
        echo $post->post_title;
    }
 ?>