I’m interested in finding out how to do this but also the reason
behind it.
I haven’t tested your code (the conditional stuff), but from what I could see:
The Reason
The AJAX action is the same for both the front page and category AJAX requests:
-
myloadmore.js
var data = { 'action': 'loadmore', // <- same as below action 'query': misha_loadmore_params.posts, 'page' : misha_loadmore_params.current_page };
-
catloadmore.js
var data = { 'action': 'loadmore', // <- same as above action 'query': cat_loadmore_params.posts, 'page' : cat_loadmore_params.current_page };
And in functions.php
, there are two callbacks (cat_loadmore_ajax_handler
and misha_loadmore_ajax_handler
) hooked to the AJAX action named loadmore
. These callbacks would both be called when an AJAX request was made where the action is loadmore
, no matter the request came from the front page or a category archive.
But you call wp_die()
(which is similar to calling die
or exit
) from within the callbacks, so once the cat_loadmore_ajax_handler()
is called, the other callback will not going to run since the script execution has ended. So that’s why:
catloadmore.js – This one works on category.php AND front-page.php even though I’m not calling it on front-page.php.
The “How To” (fix the issue)
Use different actions:
-
myloadmore.js
var data = { 'action': 'myloadmore', ... };
-
catloadmore.js
var data = { 'action': 'catloadmore', ... };
And in functions.php
:
-
For the front page:
// AJAX action: myloadmore add_action( 'wp_ajax_myloadmore', 'misha_loadmore_ajax_handler' ); // Authenticated users add_action( 'wp_ajax_nopriv_myloadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users
-
For category pages:
// AJAX action: catloadmore add_action( 'wp_ajax_catloadmore', 'cat_loadmore_ajax_handler' ); // Authenticated users add_action( 'wp_ajax_nopriv_catloadmore', 'cat_loadmore_ajax_handler' ); // Non-authenticated users