woothemes/woocommerce — Issue #408: Weirdness, maybe bug: woocommerce_query overwrites posts_per_page in custom WP_Query
Author: feedmeastraycat
Created: 2011-12-22 13:06:15+00:00
State: open

Not sure if this is a bug. Or a feature. :) But it acts as a bug for me. And I don't think it's been here since WooCommerce 1.0. Working on a plugin for WooCommerce and came back to the code after some weeks of idle. So I'm not 100% sure if it's a new thing or I just never noticed it before.

Anyway. When doing this:

$posts = new WP_Query(array(
'post_type' => 'product',
'posts_per_page' => 1,
'paged' => 5
));

I get page 5, with 1 product, as expected.
But when I do the same thing through an Ajax-call the ```woocommerce_query``` object comes in with the ```parse_query()``` function and the following line changes posts_per_page to the default value:

$q->set( 'posts_per_page', apply_filters('loop_shop_per_page', get_option('posts_per_page')) );

In my test I only get this in an ajax call. Not sure why that is. If that has something to do with in which order code is being executed or something.

This is my test.php plugin. If you add and activate it, it will create a page. That page will load the code above and just a print_r() on the $post variable. You can see (at least in my setup) that posts_per_page is 1. But if you click the "Test" link it runs the same code through an ajax-call. And (at least in my setup) posts_per_page gets changed into 12.

<?php
/*
Plugin Name: Test
Plugin URI: http://www.feedmeastraycat.net/
Description: Test
Author: David Mårtensson <david.martensson@gmail.com>
Version: 0.1
Author URI: http://www.feedmeastraycat.net/
*/

add_action('init', 'test_init');
function test_init() {

wp_enqueue_script('jquery');

}

add_action( 'wp_ajax_test', 'ajax__test' );
function ajax__test() {

if ( !wp_verify_nonce( $_POST['nounce'], 'test-ajax-nounce' ) ) {
header("HTTP/1.0 404 Not Found");
die;
}

$posts = new WP_Query(array(
'post_type' => 'product',
'posts_per_page' => 1,
'paged' => 5
));
echo "<pre>";
print_r($posts);
echo "</pre>";

die;

}

add_action( 'admin_menu', 'test_admin_menu' );
function test_admin_menu() {
add_menu_page('Test', 'Test', 'administrator', "test_page", 'test_page');
}

function test_page() {

$url = admin_url( 'admin-ajax.php' );

?>
<script language="javascript" type="text/javascript">
function test() {
var ajax = jQuery.ajax({
type: 'POST',
url: '<?php echo $url ?>',
data: {
'action':'test',
'nounce':'<?php echo wp_create_nonce( 'test-ajax-nounce' ) ?>'
},
success:function(response) {
jQuery('#test-ajax-content').html(response);
}
});
}
</script>
<div class="wrap">
<p><a href="javascript:test();">Test</a></p>
<div id="test-ajax-content">
<strong>Non-ajax:</strong><br/>
<?php
$posts = new WP_Query(array(
'post_type' => 'product',
'posts_per_page' => 1,
'paged' => 5
));
echo "<pre>";
print_r($posts);
echo "</pre>";
?>
</div>
</div>
<?php
}