简体   繁体   中英

using WP_Query with custom SQL in wordpress

I am writing a plugin for wordpress and I want to create my own search. I have tried to alter the wordpress search, but what I am doing is very specific with the SQL query. I am comparing lat and long coordinates and getting posts based on that.

I can display posts by using the standard wpdb query, but then I don't get the other features like paging. I'd like to be able to use my SQL statement with the WP_Query function. If I'm right in thinking, I should then be able to use the paging and other features which come from the $posts global variable.

Is this right?? I've googled for hours but can't find anything for plugins outside of using args to select categories etc. I simply need to send a complete SQL command - nothing else.

Many thanks....

您可能并没有获得最优化的SQL查询,但是,如果获得要使用的所有帖子ID的数组(首先使用自己的SQL),然后使用WP_Query以及参数post__inposts_per_page ,WordPress将为您处理一切(包括SQL限制,分页等)。

For the benefit of anyone finding this, as of WordPress 3.1 you can now use a filter to directly alter the SQL used by $wp_query. See codex for more info.

There's a filter named posts_where_paged that will give you the WHERE portion of the SQL query that's being generated. Modify that with your extra needed SQL comparisons. This way you don't change the way WordPress loads the page, you just change the data that it retrieves from the database.

If the data that you're pulling isn't in the normal set of tables that is queried during search then you will also have to alter the tables being looked at with the posts_join_paged filter. (at least I think it's that one ;) )

Look around line 2376 of wp-includes/query.php to see the filters you can use to modify the db query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM