Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using Ajax to load posts into a sidebar that are filtered by a chosen category. It works perfectly fine the first time, but for some reason the second time it loads a mixture of results from the first category and the second category. Does anyone know why this is happening?

Here is my Javascript:

function load_blog_posts_function(str) 
 {
 jQuery.ajax({
 type: "GET",
 url: "wp-admin/admin-ajax.php",
 dataType: 'html',
 data: ({action : 'load_blog_posts_sidebar', symbol:str}),
 success: function(data) {
 $('.rpwe-ul').html(data);
 $("#left-sidebar").width(347);
 }
 });
 }

PHP

function load_blog_posts_sidebar()
{
$stockSymbol = $_GET['symbol'];
$args = array('posts_per_page' => 3, 'category' => get_cat_ID($stockSymbol));
$rpwewidget = get_posts($args);
global $post;
foreach ( $rpwewidget as $post ) : setup_postdata( $post ); ?>

<li class="rpwe-clearfix">

        <?php if ( has_post_thumbnail() ) {  ?>

            <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'rpwe' ), the_title_attribute('echo=0' ) ); ?>" rel="bookmark">
                <?php the_post_thumbnail( 
                    array( 45, 45, true ),
                    array( 
                        'class' => 'rpwe-alignleft' . ' rpwe-thumb the-post-thumbnail',
                        'alt'   => esc_attr( get_the_title() ),
                        'title' => esc_attr( get_the_title() ) 
                    ) 
                ); ?>
            </a>
    <?php } 

    <h3 class="rpwe-title">
        <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'rpwe' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
    </h3>
        <time class="rpwe-time published" datetime="<?php echo esc_attr( get_the_date( 'c' ) ); ?>"><?php echo get_the_date(); ?></time>
</li>
<?php endforeach; wp_reset_postdata();
die();
}

I was reading that this might be from the use of the global $post variable (the query doesn't reset?), however I tried using both wp_reset_postdata() and wp_reset_query() and it still doesn't work.

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.