第一次进行自定义查询。我在寻找一种方法来获取某个分类法的类别列表,以便可以为自动完成函数运行类似的查询。为了得到一些结果,我提出了mysql查询,它在phpMyAdmin中给出了结果
SELECT *
FROM wp_terms
INNER JOIN wp_term_taxonomy ON ( wp_terms.term_id = wp_term_taxonomy.term_id )
WHERE wp_terms.name LIKE \'ca%\'
AND count >0
LIMIT 0 , 30
我的wordpress函数如下所示
function get_categories_by_like_searching() {
global $wpdb;
$keyword = $_GET[\'query\']; // example : "ca" would return categories with name of "cats"
$query = $wpdb->prepare( "SELECT * FROM $wpdb->wp_terms
INNER JOIN $wpdb->wp_term_taxonomy
ON ($wpdb->wp_terms.term_id = $wpdb->wp_term_taxonomy.term_id)
WHERE $wpdb->wp_terms.name LIKE %s AND $wpdb->wp_terms.count > 0", $wpdb->esc_like($keyword) . \'%\');
$categories = $wpdb->query($query);
foreach($categories as $category) {
array_push($results,$category[\'name\']);
}
$results = array("suggestions"=>$results);
$response = json_encode($results);
// response output
header( "Content-Type: application/json" );
echo $response;
exit;
}
我是否连接错误,或者wordpress查询语法是否已关闭?
我要寻找的确切函数实际上是:
<?php
$args = array(
\'taxonomy\' => \'my_custom_taxonomy\'
// with category names LIKE \'x%\'
);
$categories = get_categories($args);
?>
SO网友:karpstrucking
您包括了表前缀,但$wpdb会处理这个问题。
更改:
$query = $wpdb->prepare( "SELECT * FROM $wpdb->wp_terms INNER JOIN $wpdb->wp_term_taxonomy ON ($wpdb->wp_terms.term_id = $wpdb->wp_term_taxonomy.term_id) WHERE $wpdb->wp_terms.name LIKE %s AND $wpdb->wp_terms.count > 0", $wpdb->esc_like($keyword) . \'%\');
收件人:
$query = $wpdb->prepare( "SELECT * FROM $wpdb->terms INNER JOIN $wpdb->term_taxonomy ON ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id) WHERE $wpdb->terms.name LIKE %s AND $wpdb->terms.count > 0", $wpdb->esc_like($keyword) . \'%\');
(再次检查,以防我遗漏任何内容)