How to use external API content in place of WP posts using $wp_query?

Question

I am trying to find a way to intercept the main $wp_query in order to use content from an external API in place of the local WordPress posts.

This is a little more involved than similar questions I’ve come across simply asking how to display content from an external API, so I’ll try and clarify what I need to do:

The client is moving from an existing WP site, to a new one as well as a mobile app. This means that content is being served from an external API system, instead of WordPress, to be used in both the new website and the mobile app. There are some sections that they want to carry over from the old site (such as woocommerce), which is why we are still using WP for the new site.

I need to find a way to get the wp_query to return “posts” that are actually content pulled from this external API query. The new site needs to be able to be updated by non-technical people, so we are building it with Elementor page builder plugin, but that means that I can’t just use shortcodes everywhere to pull and display the content. It also means that it needs to work with the loop of WordPress. This content needs to be up to date with minimal caching, so using plugins I found that parse an external API request and populate posts in WP are not an option either.

I have found posts referencing things like ‘pre_get_posts’ and query_posts(), but these just alter the query, not the results.

Is there a way to modify or add to the $wp_query result before it is used in the loop? I was thinking of creating custom post types, then populating a list (inline during the request, not stored in the DB) of them with content using wp_remote_get() similar to this:

add_filter('the_content', 'my_content_178750', 1, 99);

function my_content_178750($content) {
    return wp_remote_retrieve_body(wp_remote_get('http://example.com'));
} 

but using a filter for when a custom post type is queried in place of ‘the_content’, but I haven’t had much success yet, and don’t know how that would be extended to a list of posts.

0
, Steve 3 years 2020-06-02T16:10:22-05:00 0 Answers 99 views 0

Leave an answer

Browse
Browse