How to use global $wp_query with custom queries?

I have a question very similar to this one here, which is still unresolved.

I am using a very simple plugin that gets the pagination information from a page, and then adds a button to load more content. This works well on the search and archive pages, which have a main query. However, it isn’t working on pages with custom queries, ex: $the_query = new WP_Query($args);

And I know the reason for this is because the javascript for the plugin uses global $wp_query, ex:

function pbd_alp_init() {
global $wp_query;
//adds scripts and localizes
}
add_action(‘wp_enqueue_scripts’, ‘pbd_alp_init’);

If I replace the global query, it works with the custom query page:

function pbd_alp_init() {
$wp_query = new WP_Query( array(‘post_type’ => ‘post’,’post_status’ => ‘publish’,’category_name’ => ‘stories’,’paged’ => get_query_var(‘paged’)));
//adds scripts and localizes
}
add_action(‘wp_enqueue_scripts’, ‘pbd_alp_init’);

I can’t help but feel though, that this is the entirely wrong way to go about a long-term solution. Is there any way to retrieve the custom query from the page and insert it into the plugin’s function?

Read more here:: How to use global $wp_query with custom queries?

Leave a Reply

Your email address will not be published. Required fields are marked *