1

If I use the following function in any theme template, it works as expected. However when trying to use it within an AJAX function in my functions.php, it returns empty.

$args = array (
        'numberposts' => 10,
        'post_type' => array('topic','reply'),
        'author' => 454
    );
$user_posts = get_posts($args);

Any ideas?

Here is the full function:

function he_delete_user(){

    $args = array (
        'numberposts' => 10,
        'post_type' => array('topic','reply'),
        'author' => 454
    );
    $user_posts = get_posts($args);

    if (empty($user_posts)){
        $response_array['status'] = 'false';    
        echo json_encode($response_array);
    }
    else{
        // delete all the user posts
        foreach ($user_posts as $user_post) {
            wp_delete_post($user_post->ID, true);
        }
        $response_array['status'] = 'success';    
        echo json_encode($response_array);
    }
}
add_action('wp_ajax_he_delete_user','he_delete_user');
  • 5
    can we see this in the context of your ajax function? are you sure the ajax function is executing and this code is actually running? – Milo Dec 6 '13 at 3:18
  • Added, but I have verified that it's running using the json response implemented in the function. The only issue is that get_posts returning nothing. – jetlej Dec 7 '13 at 15:10
  • 1
    This is going to require debugging. Instead of get_post, create a WP_Query object. Then dump out (var_dump) the value of $my_query->request to see if there are any differences between the SQL. – Seamus Leahy Dec 8 '13 at 1:58
  • If I do that, it shows that it's asking for posts! Not topics and replies. My syntax is verified correct, so I'm not sure why that's happening... – jetlej Dec 9 '13 at 14:20
  • Seems to be the same issue: wordpress.stackexchange.com/questions/62401/… – jetlej Dec 9 '13 at 14:37
0

This is a bandaid, not a fix. But it seems there is a bug within WP_Query, so I had to modify the query right before it was actually run in order for the post_type parameter to not be ignored.

1) I changed get_posts() to a WP_Query

2) I added this to my functions.php file:

function ban_parse_wp_query( $query ) {
    $query->set( 'post_type', array('topic','reply') );
    return $query;
}

3) Then I modified the query with that action right before it was run and then remove the action right after so it would not affect any other queries:

add_filter( 'pre_get_posts', 'ban_parse_wp_query' );
$user_posts = new WP_Query($args);
remove_filter( 'pre_get_posts', 'ban_parse_wp_query' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.