【发布时间】:2013-04-12 17:13:16
【问题描述】:
我正在开发一个 Wordpress 插件,需要使用我使用插件创建的自定义表格来订购网站的帖子。
我不想更改主题中的代码,所以我在 codex 上找到了过滤器 posts_orderby 和 posts_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
它有效。
所以我的插件文件中编写的代码有问题,但我无法弄清楚。
【问题讨论】:
-
好的,我部分解决了我的问题。我在
custom_join()函数中添加了另一行代码。现在的代码是这样的:function custom_join($join){} -
好的,我把评论弄得一团糟。代码是这样的:好的,我部分解决了我的问题。我在
custom_join()函数中添加了另一行代码。现在的代码是这样的: function custom_join($join){ global $wpdb; $customTable = $wpdb->prefix.'custom_table'; if(!is_admin()){ $join .= " LEFT JOIN wp_postmeta t1 ON wp_posts.ID = t1.post_id"; $join .= " 左连接 $customTable t2 ON t1.meta_value = t2.slug"; } 返回 $join;它可以工作,但还有其他问题。现在我看到一些帖子重复了。
标签: php mysql wordpress add-filter