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 have a page that currently loads posts of custom post type using regular WP_Query. The custom post type are for news articles. Newer news articles (posts) are constantly written, as such there is a need for loading newer posts without having the user to refresh the page.

The effect I am desiring is similar to what one can find on Facebook or Twitter. Whenever there is a new post or tweet on these sites, the newer post is automatically added to the top of the posts already displayed.

Any code snippets or ideas on how to get this done?

Regards, John

share|improve this question
    
How is this a WordPress question, and not a script/AJAX question? You already showed that you know how to query the posts, which is the primary WordPress-related part of the question. –  Chip Bennett Jan 23 '12 at 20:55
    
John, was my answer helpful? If so, please mark it as the correct answer. –  DigitalSea Feb 20 '12 at 7:22
    
@Dwayne I had a lot of changes made to the initial backend code on which this would be based. I'll have to try this out once the underlying code is finalized. –  John Feb 20 '12 at 8:25
    
No worries John. Do let me know how it goes and if you need any help getting my code example to work with the site you're developing. –  DigitalSea Feb 20 '12 at 22:08
add comment

2 Answers

up vote 1 down vote accepted

I was in the same situation as you recently. The way I did it is probably wrong, and prone to bugs but if you can live with that then this might help.

Basically you create an empty array at the top of your loop file, say for example loop-index.php.

$ignores = array();

Then inside your post loop you want to add these post IDs to the array (inside your while loop).

$ignores[] = $post->ID;

Then you'll obviously have a link which can be clicked to show more posts with a Javascript click event binded too it presumably using jQuery. On the link set a rel tag to be the array of ID's, you'll have to do a foreach over the array and separate each by a comma.

Then in the loop template looking for the GET variable being passed from the AJAX url and use a post__not_in conditional on your WP_Query so it doesn't load in those ID's of already loaded posts.

If you need example code, I would be happy to write you an example.

I was in the same situation as you recently. The way I did it is probably wrong, and prone to bugs but if you can live with that then this might help.

Basically you create an empty array at the top of your loop file, say for example loop-index.php.

$ignores = array();

Then inside your post loop you want to add these post IDs to the array (inside your while loop).

$ignores[] = $post->ID;

Then you'll obviously have a link which can be clicked to show more posts with a Javascript click event binded too it presumably using jQuery. On the link set a rel tag to be the array of ID's, you'll have to do a foreach over the array and separate each by a comma.

Then in the loop template looking for the GET variable being passed from the AJAX url and use a post__not_in conditional on your WP_Query so it doesn't load in those ID's of already loaded posts.

If you need example code, I would be happy to write you an example.

** Update w/ Example Code **

<div id="posts">
    <?php

        $numposts = wp_count_posts('post');
        $numposts = $numposts->publish;

        // Posts per page
        $per_page = 9;

        // Determine total amount of pages
        $total_pages = ceil($numposts / $per_page);

        // Get current page
        $paged      = (get_query_var( 'page' )) ? get_query_var( 'page' ) : 1;

        // Above your loop
        $ignores = array();

        // If we have sent ignore ID's
        if ( $_GET['ignore'] )
        {
            $get_ignores = trim($_GET['ignore'], ',');
            $get_ignores = explode(',', $get_ignores);
        }

        // If we have ignore ID's
        if ( !empty($get_ignores) )
        {
            foreach ($get_ignores AS $k => $v)
            {
                $ignores[] = $v;
            }
        }

        $count = 1;

        $my_args = array(
            'posts_per_page' => 9,
            'paged'          => get_query_var( 'page' ),
            'post__not_in'   => $ignores,
            'post_status'    => 'publish'
        );                                  

        $my_query   = new WP_Query($my_args);

        if ( $paged <= $total_pages):
            $paged = $paged + 1; 

            // The loop
            while ( $my_query->have_posts() ): $my_query->the_post();
                // At the start of the loop populate the used post ID's
                $ignores[] = $post->ID;
    ?>
        <div class="post">
        <h2><?php the_title(); ?></h2>
        </div>
    <?php $count++; endwhile; endif; ?>
    <?php 

        if ( $ignores AND is_array($ignores) )
        {
            // Create a comma separated string of ignore ID's
            foreach ( $ignores AS $k => $v ) {
                $ignore_str .= $v.',';
            }

            // Trim the ignore string of any rogue commas
            $ignore_str = ltrim($ignore_str, ',');
            $ignore_str = rtrim($ignore_str, ',');

            $ignore = site_url('page/'.$paged.'/?ignore='.$ignore_str.'');
        }

    ?>

<a href="#" rel="<?php echo $ignore; ?>" id="load-more">Load More Posts</a>

</div>

<?php if ( !$my_query->have_posts() ) : ?>

    <section id="no-posts">
        <div id="post-0" class="post error404 not-found">
            <h1 class="entry-title"><?php _e( 'Not Found', 'twentyten' ); ?></h1>
            <div class="entry-content">
                <p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'twentyten' ); ?></p>
            </div>
        </div>
    </section>
<?php endif; ?>

<script type="text/javascript">
(function($){
    $("#load-more").on('click', function(e) 
    {
        e.stopImmediatePropagation();

        $("#posts").append("<div id='loading'><p>Loading posts</p></div>");

        $("<div>").load($(this).prop('rel') + ' #posts', function() 
        {
            $('#posts').append($(this).find("#posts").html()).fadeIn('slow');
            $("#loading").remove();
        });

        if ($("#no-posts"))
        {
            $("#no-posts").remove();
            $("#load-more").remove();   
        }

        e.preventDefault();

    });
 })(jQuery);
</script>
share|improve this answer
    
Thx for the reply. Even I thought this would require some twisted code as this cannot be achieved by normal means using standard Wordpress routines. Your solution appears as a good workaround. I'll try and keep you posted on the same. –  John Nov 14 '11 at 21:17
    
No worries John, I'm here to help. See my updated answer for a code example, it might have a few errors and whatnot, but it should help you work on a solution. Another way that is probably easier would be to set session values and do it that way, not sure if it would work properly though. –  DigitalSea Nov 15 '11 at 6:03
add comment

I found the solution,but very hard explane,but I try...
Step by step:

First you need open the index.php and paste this code:

<script>
(function($) {
  $(document).ready(function() {
    var refreshId = setInterval(function()
    {
      $('#content').fadeOut("fast").load('new.php').fadeIn("fast");
    }, 30000);
  });
})(jQuery);

</script>

And you need change the id in funcktion to your div ID(so the '#content' part).

Step 2: Crate a file,name is new.php.
The file place in your wwww map or public_html.
The file content:

<?php require_once("wp-blog-header.php"); ?>

And you must find on the theme post hooks,example for my theme:

<div id="content" <?php cyberchimps_filter_content_class(); ?>>

        <?php do_action( 'cyberchimps_before_content'); ?>

        <?php if ( have_posts() ) : ?>

            <?php while ( have_posts() ) : the_post(); ?>

                <?php get_template_part( 'content', get_post_format() ); ?>

            <?php endwhile; ?>

        <?php elseif ( current_user_can( 'edit_posts' ) ) : ?>

            <?php get_template_part( 'no-results', 'index' ); ?>

        <?php endif; ?>

        <?php do_action( 'cyberchimps_after_content'); ?>

    </div>

If you find this part somewhere,paste UNDER the <?php require_once("wp-blog-header.php"); ?>.
When you're done, you should find the file in which to determine the how much of the div (my div name is "#content") of and must be add !important atribute for the with.
Example:

min-width:850px !important;

final step:
Set the links type:
wp-admin-->permalinks-->Default post type
That's it have fun.
Thx for help for help to murdaugh on this page .

share|improve this answer
add comment

Your Answer

 
discard

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

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