You have use ajaxurl
when make post request - it\'s right way but it also mean that now $wp_query
, in your my__load__more()
function, work with your.site/wp-ajax
url instead of your.site/taxonomy
. That\'s why you couldn\'t get category name from $wp_query->query_vars
.
First, I use add_action( \'wp_enqueue_scripts\', \'my__enqueue\' );
for enqueue your scripts (see example below).
Second, I change arguments you pass to wp_localize_script()
function. I offer get name of category when you add script to page instead of get it inside ajax handler:
add_action( \'wp_enqueue_scripts\', \'my__enqueue\' );
function my__enqueue(){
wp_enqueue_script( \'my__load__more\', get_template_directory_uri() . \'/assets/js/load_more.js\', array( \'jquery\' ), \'1.0.0\', true );
global $wp_query;
$vardi = $wp_query->query_vars;
$category = isset( $vardi[ \'category_name\' ] ) ? $vardi[ \'category_name\' ] : \'\';
$ajaxurl = admin_url( \'admin-ajax.php\' );
wp_localize_script( \'my__load__more\', \'my__params\', array(
\'ajaxurl\' => $ajaxurl,
\'category\' => $category,
) );
}
Of course, you could add parameter category
in same way you add ajaxurl
in your code:
wp_localize_script( \'my__load__more\', \'my__category\', $category );
Pay attention
If you are going to use array
in wp_localize_script()
function note that now you need use it in your js code as an object element, e.g., my__params.ajaxurl
instead of ajaxurl
Third, we need to change your post call:
$.post(my__params.ajaxurl, // if you use array
{
\'action\': \'my__load__more\',
\'addNum\': addNum,
\'getChoose\': getChoose,
\'category\': my__params.category, // pass category to handler
}
Fourth, and last, change handler:
function my__load__more(){
// this is your handler beginning
$args__load = array(
\'posts_per_page\' => -1,
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
);
if( !empty( $_POST[ \'category\' ] ) ) $args__load[ \'category_name\' ] = $_POST[ \'category\' ];
$articles = new WP_Query( $args__load );
// this is your handler ending
}
Value in $_POST[ \'category\' ]
could be empty, so we no need to use it in our query. Sure, you could add it directly to $args__load
array with other parameters without any if
, as you want.
Hope it helps ;)