wordpress posts_orderby filter with custom table in plugin

风格不统一 提交于 2019-12-06 17:05:43

Ok, I solved it.

The problem is that the post query doesn't include the postmeta table, so I added it on the custom_join function, like this:

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;
}

I added also the posts_groupby filter because the new query gave me duplicated posts (lots of duplicated posts).

Here's the code:

add_filter('posts_groupby','custom_groupby');

function custom_groupby($groupby){
    global $wpdb;

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

    return $groupby;
}

Everything is written in the plugin file, but you can write also in the function.php file of your theme.

Remember to include the if(!is_admin) statement if you want to see the custom query only on front end.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!