我有一个自定义的 WP 3.5 函数,我不知道为什么它不起作用...我确定错误在SQL查询中。该函数试图做的是从特定类别获取帖子的帖子以$ post_name开头。
function get_post_like_slug($post_name) {
global $wpdb;
$page_name = substr($post_name, 0, -1).'%';
$id = $wpdb->get_var( $wpdb->prepare("SELECT $wpdb->posts.ID FROM $wpdb->posts LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id) WHERE ($wpdb->term_relationships.term_taxonomy_id = 5 AND $wpdb.post_name LIKE %s)", $post_name ));
if ( $id )
return ($id);
return null;
}
答案 0 :(得分:0)
在另一篇关于正确使用wordpress语句的帖子中看到这个。
可能是这样的:
$id = $wpdb->get_var( $wpdb->prepare("SELECT $wpdb->posts.ID FROM
$wpdb->posts LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID =
$wpdb->term_relationships.object_id) WHERE
($wpdb->term_relationships.term_taxonomy_id = 5 AND $wpdb.post_name
LIKE %s)", '%' . like_escape($post_name) . '%' ));
答案 1 :(得分:0)
我找到了解决方案!我做的是先添加“$ wpdb->”在每个表名和转义%字符(%%)上。以下功能现在可以使用:
function get_post_like_slug($post_name) {
global $wpdb;
$post_name = substr($post_name, 0, -1);
$id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts LEFT JOIN $wpdb->term_relationships ON $wpdb->posts.ID = $wpdb->term_relationships.object_id WHERE post_name LIKE %s AND $wpdb->term_relationships.term_taxonomy_id=5 LIMIT 1", $post_name.'%%' ));
if ( $id )
return ($id);
return null;
}