wpdb查询

1、本地开发

$cat_id=$GLOBALS['cat_information'];
$kw_array = $GLOBALS['wpdb']->get_results("SELECT ID,post_title,post_date FROM wp_posts,wp_term_relationships,wp_term_taxonomy
 WHERE ID=object_id
 and wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
 and wp_term_relationships.term_taxonomy_id = $cat_id
 and taxonomy = 'category' LIMIT 5
 ");
var_dump($kw_array);

此方法线上环境不支持多表查询:

$kw_array = SELECT ID,post_title,post_date,post_content
    FROM wp_posts,wp_term_relationships,wp_term_taxonomy
    WHERE ID=object_id
    and wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
    and wp_term_relationships.term_taxonomy_id = $cat_id
    and taxonomy = 'category' and post_content LIKE %s order by ID desc LIMIT $num", '%' . $GLOBALS['wpdb']->esc_like($GLOBALS['seo_keyword']) . '%'
   
var_dump($kw_array);

$cat_id=get_category_by_slug('beginners-tutorial')->term_id;;
$kw_array = $GLOBALS['wpdb']->get_results($GLOBALS['wpdb']->prepare(
    "SELECT *
    FROM wp_posts,wp_term_relationships
    WHERE ID=object_id
   and post_content LIKE %s order by ID desc LIMIT 3", '%' . $GLOBALS['wpdb']->esc_like($GLOBALS['seo_keyword']) . '%'
));
var_dump($kw_array);
function query_fun($cat_id,$num){
    $kw_array = $GLOBALS['wpdb']->get_results($GLOBALS['wpdb']->prepare(
        "SELECT ID,post_title,post_date,post_content
    FROM wp_posts as m
    LEFT JOIN wp_term_relationships ON(m.ID = wp_term_relationships.object_id)
    LEFT JOIN wp_term_taxonomy ON(wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
    LEFT JOIN wp_terms ON(wp_term_taxonomy.term_id = wp_terms.term_id)  
    WHERE m.post_status = 'publish'
    AND wp_terms.term_id = $cat_id
    AND m.post_title LIKE %s 
    ORDER BY m.post_date DESC LIMIT $num", '%' . $GLOBALS['wpdb']->esc_like($GLOBALS['seo_keyword']) . '%'
    ));

    // 获取数量不足,最近的300个文章中随机显示4个
    if(sizeof($kw_array)<$num){
        $sql="SELECT ID,post_title,post_date,post_content
    FROM wp_posts as m
    LEFT JOIN wp_term_relationships ON(m.ID = wp_term_relationships.object_id)
    LEFT JOIN wp_term_taxonomy ON(wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
    LEFT JOIN wp_terms ON(wp_term_taxonomy.term_id = wp_terms.term_id)  
    WHERE m.post_status = 'publish'
    AND wp_terms.term_id = $cat_id
    ORDER BY rand() desc LIMIT 300";
        $kw_array=$GLOBALS['wpdb']->get_results($sql);
    }
    return $kw_array;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容