wordpress posts_orderby filter with custom table i

2019-06-06 11:07发布

I'm developing a Wordpress plugin and need to order the posts of the site with the custom table that I created with my plugin.

I don't want to alter the code within the theme so I found on codex the filters posts_orderby and posts_join (found here: https://codex.wordpress.org/Custom_Queries).

The custom table have these values:

ID    slug    price 

and in the plugin file where I added these lines:

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

When I refresh the index page it gives me this error message:

No Results Found

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

I tried to do the query directly on my database with this code:

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

and it works.

So there's something wrong in the code written in my plugin file but I can't figure it out.

1条回答
在下西门庆
2楼-- · 2019-06-06 11:34

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.

查看更多
登录 后发表回答