【问题标题】:wordpress posts_orderby filter with custom table in pluginwordpress posts_orderby 过滤器与插件中的自定义表
【发布时间】:2013-04-12 17:13:16
【问题描述】:

我正在开发一个 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

它有效。

所以我的插件文件中编写的代码有问题,但我无法弄清楚。

【问题讨论】:

  • 好的,我部分解决了我的问题。我在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


【解决方案1】:

好的,我解决了。

问题是post查询不包含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) 语句。

【讨论】:

    猜你喜欢
    • 2015-03-15
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2019-01-01
    • 1970-01-01
    • 2010-12-13
    相关资源
    最近更新 更多