Retrieveing data using get_posts or WP_Query can be challenging when we need to include custom tables in the query. In this tutorial, we will learn how to include our custom tables to create custom queries. The idea for this tutorial came while working on my plugin Simple Sponsorships. I had to retrieve sponsors by packages and also by the content they sponsor.
This plugin has a custom wrapper function ss_get_sponsors( $args = array() ) which basically passes the arguments to the get_posts function.
I could have built new functions but I wanted for me and other developers to have an easier API so I decided to stick only with one function.
Here are two challenges:
How to get sponsors by a package when the packages are saved in a custom table,
How to get sponsors by the content they sponsor which is also saved in the wp_posts table.
The first challenge should be quite easy to handle since there is a third table sponsorships which has two columns sponsor and package and contains IDs of both. So I had to join this table with the wp_posts table to get the data.
The second challenge was a bit tricky. The content that is sponsored by the Sponsor, has its meta table updated with the meta_key
Source: https://managewp.org/articles/18373/extending-wp-query-with-custom-queries-and-tables
source https://williechiu40.wordpress.com/2019/02/12/extending-wp_query-with-custom-queries-and-tables/
No comments:
Post a Comment