wordpress posts_orderby在插件中使用自定义表进行过滤

时间:2013-04-12 17:13:16

标签: php mysql wordpress add-filter

我正在开发一个Wordpress插件,需要使用我使用我的插件创建的自定义表来订购网站的帖子。

我不想更改主题中的代码,因此我在codex上找到了过滤器posts_orderbyposts_join(在此处找到:https://codex.wordpress.org/Custom_Queries)。

自定义表具有以下值:

ID    slug    price 

并在我添加这些行的插件文件中:

add_filter('posts_orderby','custom_orderby');
add_filter('posts_join','custom_join');

function custom_join($join){
    global $wpdb;
    $customTable = $wpdb->prefix.'custom_table';

    if(!is_admin()){
        $join .= " LEFT JOIN $customTable ON $wpdb->postmeta.meta_value = $customTable.slug";
    }
    return $join;
}
function custom_orderby($orderby_statement){
    global $wpdb;
    $customTable = $wpdb->prefix.'custom_table';

    if(!is_admin()){
        $orderby_statement = "$customTable.price DESC"; 
    }
    return $orderby_statement;
}

当我刷新索引页面时,它给出了以下错误消息:

No Results Found

The page you requested could not be found. Try refining your search, or use the navigation above to locate the post.

我尝试使用以下代码直接在我的数据库上执行查询:

SELECT * FROM wp_posts t1
    LEFT JOIN wp_postmeta t2 ON t1.ID = t2.post_id
    LEFT JOIN wp_custom_table t3 ON t2.meta_value = t3.slug

ORDER BY t3.price DESC

它有效。

所以在我的插件文件中编写的代码有问题,但我无法理解。

1 个答案:

答案 0 :(得分:4)

好的,我解决了。

问题是帖子查询不包含postmeta表,所以我在custom_join函数上添加了它,如下所示:

add_filter('posts_join','custom_join');
add_filter('posts_orderby','custom_orderby');

function custom_join($join){
    global $wpdb;
    $customTable = $wpdb->prefix."custom_table";

    if(!is_admin){
        $join .= "LEFT JOIN $wpdb->postmeta p1 ON $wpdb->posts.ID = p1.post_id";
        $join .= "LEFT JOIN $customTable p2 ON p1.meta_value = p2.slug";
    }

    return $join;
}

function custom_orderby($orderby_statement){
    global $wpdb;

    if(!is_admin){
        $orderby_statement = "p2.price DESC, $wpdb->posts.post_date DESC";
    }

    return $orderby_statement;
}

我还添加了posts_groupby过滤器,因为新查询给了我重复的帖子(很多重复的帖子)。

以下是代码:

add_filter('posts_groupby','custom_groupby');

function custom_groupby($groupby){
    global $wpdb;

    if(!is_admin){
       $groupby = "$wpdb->posts.ID";
    }

    return $groupby;
}

所有内容都写在插件文件中,但您也可以在主题的function.php文件中写入。

如果您希望在前端看到自定义查询 ,请务必添加if(!is_admin)语句。