0

我有一个自定义的WP 3.5函数,但我不知道为什么它不起作用......我确定错误在 SQL 查询中。该函数试图做的是从特定类别中获取帖子,其中帖子的 slug 以 $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;
}
4

2 回答 2

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;
}
于 2013-01-07T01:47:03.827 回答
0

在另一篇关于在 wordpress 中正确使用 like 语句的帖子中看到了这一点。

可能是这样的:

$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) . '%' ));

这是帖子的链接:https ://wordpress.stackexchange.com/a/8847

于 2013-01-06T02:53:50.303 回答