简体   繁体   English

WordPress,我如何AJAX附加帖子

[英]WordPress, How Do I AJAX Additional Posts

JQUERY UPDATE JQUERY更新

<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 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(){

    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. 在阅读了几本AJAX教程之后,老实说,使用WordPress的AJAX仍然使我感到困惑:(我坚持下面的代码可以正常工作。

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. 因此,换句话说,页面最初会加载下面的循环,然后当我单击“ .load-more”按钮时,它应该通过AJAX加载更多的帖子,但被已经显示的现有帖子抵消了。

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 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回调的末尾添加wp_die()die() PHP needs to know that it's done processing. PHP需要知道它已完成处理。 Also, the nopriv event is not correct. 同样,nopriv事件也不正确。

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 解释AJAX和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. 服务器已经处理了业务逻辑,构建了HTML标记和资产,然后将它们发送到浏览器。 The server is now done. 现在服务器已完成。

AJAX gives you the means to call back to the server and have it do more processing for you. AJAX使您可以回调服务器,并为您执行更多处理。 The cycle is: 周期为:

  • AJAX posts back to the server AJAX回发到服务器
  • 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 . 在您的情况下,您可以使用$.post回拨到服务器。 WordPress receives the request and then fires 2 events: WordPress收到请求,然后触发2个事件:

  • 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. 如果用户已登录,则第一个事件将触发并提供访问权限。无论是否登录,第二个事件(即nopriv)都会触发。

WordPress then runs your callback that you registered to the above event names. 然后,WordPress将运行您注册到上述事件名称的回调。 Your example callback is blog_post_data_fetch() . 您的示例回调是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 . 如果是数组,则需要对其进行序列化,例如json_encode

PHP is done when it executes the die() or wp_die() construct. PHP在执行die()wp_die()构造时完成。

Now the response is sent back to jQuery. 现在,响应被发送回jQuery。 $.post receives the response. $.post收到响应。 Now you can do something with it. 现在您可以使用它来做一些事情。

In your case, your sending back some HTML markup. 您的情况是,您发回一些HTML标记。 You'll want to decide where to add this markup into the web page. 您将要决定将此标记添加到网页的位置。

Tutorials on AJAX AJAX教程

There are a lot of tutorials available to you on WordPress' implementation of AJAX: 关于WordPress的AJAX实现,有很多教程可供您使用:

Completing the Code 完成代码

I gave you the code for the PHP side (minus the nonce security check). 我为您提供了PHP方面的代码(减去了nonce安全检查)。 Next, you'll need to add the following into the jQuery script: 接下来,您需要将以下内容添加到jQuery脚本中:

  • 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. 另外,通过将WordPress的AJAX URL(可能是随机数)发送到脚本中,确保您正在本地化参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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