请帮我处理我的自定义函数get_post_by_slug
,它会尝试查询数据库并从特定类别LIKE
获取slug为something%
id=5
的帖子ID 。它一直工作到WP 3.5,但它现在已经坏了,我认为缓存可能存在问题。我为WP 3.5添加了$wpdb->prepare
,但它并没有真正解决问题。
function get_post_by_slug($post_slug) {
global $wpdb;
$post = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id WHERE post_name LIKE '%s%' AND term_taxonomy_id=5 LIMIT 1", $post_slug));
return $post;
}
提前致谢!
答案 0 :(得分:0)
prepare
与sprintf
类似,因此它会使用%
LIKE
,您可以像这样使用''
。
此外,如果您使用prepare,则应删除%s
周围的function get_post_by_slug($post_slug) {
global $wpdb;
$post_slug = '%' . $post_slug . '%';
$post = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id WHERE post_name LIKE %s AND term_taxonomy_id=5 LIMIT 1", $post_slug));
return $post;
}
,prepare会为您报价。认为下一个例子对你有用。
{{1}}
答案 1 :(得分:-2)
通过slug获取post id的最简单的解决方案是:
$your_desired_title = "yourtitle";
global $wpdb;
$id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = $your_desired_title ");
echo $id;