简体   繁体   中英

WordPress, How Do I AJAX Additional Posts

JQUERY UPDATE

<script type="text/javascript">

                    jQuery(function($){

                            function fetchBlogPosts(){

                                 $.post( ajaxUrl, {'action' : 'post_blog', 
                                                   'security' :'<?php echo wp_create_nonce('load_more_posts'); ?>' }, 
                                 function(response){

                                 });


                             }

                             $('.load-more').click(function(){
                                 fetchBlogPosts();
                             });

                        });

</script>

PHP FUNCTION UPDATE

add_action('wp_ajax_post_blog', 'blog_post_data_fetch');
add_action('wp_ajax_nopriv_post_blog', 'blog_post_data_fetch');
function blog_post_data_fetch(){

    check_ajax_referer('load_more_posts', 'security');

    ob_clean();
    get_template_part( 'inc/blog','posts' );

    wp_die();
}

After reading several AJAX tutorials and honestly AJAX with WordPress still confuses me :( I'm stuck with the following code which does work.

However, I would just like it to add additional posts to an existing loop and not repeat the same posts.

So in other words, the initial the page loads the loop below and then when I click on the ".load-more" button it should load more posts via AJAX but offset it by the existing posts already being displayed.

How is this possible to do?

FUNCTIONS.PHP

add_action('wp_ajax_post_blog', 'blog_post_data_fetch');
add_action('wp_ajax_nopriv_post_blog', 'blog_post_data_fetch');
function blog_post_data_fetch(){
    get_template_part('inc/blog','posts');
}

BLOG POSTS TEMPLATE

<?php

    $the_query = new WP_Query( array(
        'post_type' => 'blog',
    ));

    if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();


?>


<div class="carousel-cell">
    <div class="blog-item">

        <div class="featured-image">
            <a href="<?php the_permalink(); ?>">

                <?php
                    if ( has_post_thumbnail() ) :
                        the_post_thumbnail('blog-thumb');
                    else :
                ?>
                    <img src="<?php bloginfo('template_url'); ?>/img/blog-thumb.jpg" alt="">

                <?php endif; ?>

            </a>
        </div><!--/featured-image-->

        <div class="post">

            <h1><a href="#"><?php the_title(); ?>hello</a></h1>

            <?php the_excerpt(); ?>

        </div><!--/post-->


    </div><!--/blog-item-->
</div><!--/carousel-cell-->

<?php endwhile; endif; ?>

JQUERY

 function fetchBlogPosts(){

          $.post( ajaxUrl, { 'action' : 'post_blog' }, function(response){

          });
  }

      $('.load-more').click(function(){
          fetchBlogPosts();
      });

You need to add wp_die() or die() to the end of your PHP callback. PHP needs to know that it's done processing. Also, the nopriv event is not correct.

add_action('wp_ajax_post_blog', 'blog_post_data_fetch');
add_action('wp_ajax_nopriv_post_blog', 'blog_post_data_fetch');
/**
 * Processes the Ajax request for the action: post_blog.
 *
 * @since 1.0.0
 *
 * @return void
 */
function blog_post_data_fetch(){
    // You need to check the nonce here first!
    // Let's keep our web pages safe.

    // Then if the nonce is correct, you can do the
    // processing.
    ob_clean();
    get_template_part( 'inc/blog','posts' );

    // When you're done, make sure you exit PHP
    wp_die();
}

Explaining AJAX and WordPress

Let me explain what's happening.

The server has processed the business logic, built the HTML markup and assets, and then sent them out to the browser. The server is now done.

AJAX gives you the means to call back to the server and have it do more processing for you. The cycle is:

  • AJAX posts back to the server
  • Server receives the request
  • You check the nonce to make sure it's a valid request
  • Then you do some processing
  • Package up the return and send it back to the request
  • Your script receives the response and continues.

In your case, you make the call back to the server with $.post . WordPress receives the request and then fires 2 events:

  • wp_ajax_{your ajax action}
  • wp_ajax_nopriv_{your ajax action}

The first event fires and gives access if the user is logged in. The second one (ie nopriv) fires regardless if they are logged in or not.

WordPress then runs your callback that you registered to the above event names. Your example callback is blog_post_data_fetch() .

Now in your code, you need to add nonce check to keep it safe. If that passes, then you can process the request. If you are returning a string, you can echo that out (or just call the view/template file). If it's an array, then you need to serialize it, eg json_encode .

PHP is done when it executes the die() or wp_die() construct.

Now the response is sent back to jQuery. $.post receives the response. Now you can do something with it.

In your case, your sending back some HTML markup. You'll want to decide where to add this markup into the web page.

Tutorials on AJAX

There are a lot of tutorials available to you on WordPress' implementation of AJAX:

Completing the Code

I gave you the code for the PHP side (minus the nonce security check). Next, you'll need to add the following into the jQuery script:

  • send the security check (nonce)
  • process the response by adding it into the web page where you want if you get a string back

Also make sure that you are localizing the parameters by sending the AJAX URL (and maybe nonce) from WordPress to your script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM