如何在WordPress中使用Ajax-一个真实的例子

Ajax has rapidly become a popular web technology, you’ll find it used on most websites. The key feature of Ajax is it can manage database operations without reloading the web page. This means, you can fetch data from the database and display it on the front-end without needing to refresh the page.

Ajax已Swift成为一种流行的Web技术,您会在大多数网站上找到它。 Ajax的关键功能是它可以管理数据库操作,而无需重新加载Web页面。 这意味着,您可以从数据库中获取数据并将其显示在前端,而无需刷新页面。

It’s a fast and smooth way for displaying content, and as a result Ajax is now used in many various ways on a website, such as submitting blog comments, liking posts and uploading files. You can even make your website completely Ajaxified, so that each page of your site will load asynchronously.

这是一种显示内容的快速,流畅的方法,因此,Ajax现在在网站上以多种方式使用,例如提交博客评论,喜欢帖子和上传文件。 您甚至可以使您的网站完全Ajaxified ,以便您的网站的每个页面将异步加载。

Given the popularity of Ajax, most of the leading CMS platforms use it within their architecture. WordPress is no different. Actually WordPress employs Ajax in a very robust and easy way, and today I will show you just how you can use Ajax in WordPress with a real world example. Before we get started, I’ve assumed you have some knowledge of jQuery Ajax methods and WordPress hooks, as we will need both!

鉴于Ajax的流行,大多数领先的CMS平台都在其体系结构中使用它。 WordPress也不例外。 实际上WordPress以非常健壮和简单的方式使用Ajax,今天,我将向您展示如何在WordPress实例中使用Ajax。 在我们开始之前,我假设您已经了解jQuery Ajax方法和WordPress挂钩,因为我们将同时需要这两个知识!

If you’re looking for some basic WordPress development tutorials, check out WordPress Plugin Development for Beginners.

如果您正在寻找一些基本的WordPress开发教程,请查看WordPress初学者开发

WordPress jQuery UI

我们将要做什么? (What We Are Going to Make?)

You may already know that using Ajax in WordPress is slightly different than using it outside of WordPress, you’ll need to consider two things:

您可能已经知道,在WordPress中使用Ajax与在WordPress之外使用Ajax略有不同,您需要考虑两点:

  1. The URL of the WordPress admin-ajax.php file, where the data to be sent for processing.

    WordPress admin-ajax.php文件的URL,用于发送数据进行处理的位置。

  2. The Ajax action hook called wp_ajax_. You need to hook a custom function into it which will be executed during the Ajax call.

    Ajax操作挂钩称为wp_ajax_ 。 您需要将自定义函数挂接到其中,该函数将在Ajax调用期间执行。

Let’s create a plugin to understand how this works. Let’s say we want to develop a plugin that will allow users to save their favorite blog posts in a certain area so that they can read them later. This feature is useful for magazine style blogs which provide lots of content daily. It will allow logged in users to save interesting posts in a members only area, so that they can come back and read them later.

让我们创建一个插件来了解其工作原理。 假设我们要开发一个插件,该插件将允许用户将自己喜欢的博客文章保存在某个区域中,以便以后可以阅读。 该功能对于每天提供大量内容的杂志风格博客很有用。 它将使登录的用户可以在仅会员区域中保存有趣的帖子,以便他们以后可以回来阅读。

So our ‘Read Me Later’ plugin will do several things:

因此,我们的“稍后阅读”插件将执行以下操作:

  • First, we will make a link at the bottom of every blog post content.

    首先,我们将在每个博客文章内容的底部创建一个链接。
  • When a user clicks to the link, the link’s post’s ID will save in the usermeta database table without page reload.

    当用户单击链接时,链接的帖子ID将保存在usermeta数据库表中,而无需重新加载页面。
  • Finally, we will create a widget to show blog posts based on the posts IDs saved in the database.

    最后,我们将创建一个小部件以根据数据库中保存的帖子ID显示博客帖子。

Got it? Let’s do some legwork now.

得到它了? 现在让我们做些腿部工作。

准备我们的插件文件和目录设置 (Preparing Our Plugin Files and Directory Setup)

First, we’ll create a folder called read-me-later inside the plugin directory of our main WordPress installation. This folder will contain all of our files and sub-directories required for our plugin. Now inside of the read-me-later folder we will need to create another two folders called js and css.

首先,我们将在主要WordPress安装的插件目录中创建一个名为read-me-later的文件夹。 该文件夹将包含我们插件所需的所有文件和子目录。 现在,在read-me-later文件夹中,我们将需要创建另外两个名为jscss文件夹。

Then we need to create four files, which I have listed below with the proper file extensions:

然后,我们需要创建四个文件,下面列出了四个文件,并带有适当的文件扩展名:

  • read-me-later.php

    read-me-later.php

  • widget.php

    widget.php

  • read-me-later.js

    read-me-later.js

  • read-me-later. css

    read-me-later. css

The first two files will directly go in the main plugin folder. The js and css files will be put in the js and the css folders, respectively.

前两个文件将直接进入主插件文件夹。 jscss文件将分别放在jscss文件夹中。

Now we’ll populate the read-me-later.php file. Including the plugin header:

现在,我们将填充read-me-later.php文件。 包括插件头:

/**
 * Plugin Name: Read Me Later
 * Plugin URI: https://github.com/iamsayed/read-me-later
 * Description: This plugin allow you to add blog posts in read me later lists using Ajax
 * Version: 1.0.0
 * Author: Sayed Rahman
 * Author URI: https://github.com/iamsayed/
 * License: GPL3
 */

This code is important as it’s used to identify that’s it’s a plugin to WordPress. After the above code, we’ll create our main plugin class called ReadMeLater:

这段代码很重要,因为它用于标识它是WordPress的插件。 在上面的代码之后,我们将创建名为ReadMeLater主插件类:

class ReadMeLater {}

class ReadMeLater {}

包括基本JS和CSS文件 (Including Essential JS and CSS Files)

Next, we need to register and enqueue our JavaScript and CSS files with proper WordPress hooks. We’ll create several methods to perform this step. Copy this code into the ReadMeLater class:

接下来,我们需要使用适当的WordPress钩子注册和排队我们JavaScript和CSS文件。 我们将创建几种方法来执行此步骤。 将此代码复制到ReadMeLater类中:

/*
 * Action hooks
 */
public function run() {     
    // Enqueue plugin styles and scripts
    add_action( ‘plugins_loaded’, array( $this, 'enqueue_rml_scripts' ) );
    add_action( ‘plugins_loaded’, array( $this, 'enqueue_rml_styles' ) );      
}   
/**
 * Register plugin styles and scripts
 */
public function register_rml_scripts() {
    wp_register_script( 'rml-script', plugins_url( 'js/read-me-later.js', __FILE__ ), array('jquery'), null, true );
    wp_register_style( 'rml-style', plugins_url( 'css/read-me-later.css' ) );
}   
/**
 * Enqueues plugin-specific scripts.
 */
public function enqueue_rml_scripts() {        
    wp_enqueue_script( 'rml-script' );
}   
/**
 * Enqueues plugin-specific styles.
 */
public function enqueue_rml_styles() {         
    wp_enqueue_style( 'rml-style' ); 
}

The code is fairly self explanatory. Here, we’ve created a public method called register_rml_scripts(). Inside this method, we have registered our read-me-later.js and read-me-later.css files using proper WordPress functions.

该代码很容易解释。 在这里,我们创建了一个名为register_rml_scripts()的公共方法。 在此方法内部,我们已使用适当的WordPress函数注册了read-me-later.jsread-me-later.css文件。

The next two methods enqueue_rml_scripts() and enqueue_rml_styles() are used to enqueue our JavaScript and stylesheet. We’ve also created a run method, which will contain all of our action (and filter) hooks.

接下来的两个方法enqueue_rml_scripts()enqueue_rml_styles()用于使我们JavaScript和样式表入队。 我们还创建了一个run方法,它将包含我们所有的动作(和过滤器)钩子。

If you’re new to WordPress, you can check out Enqueuing Scripts and Styles in WordPress by Younes Rafie, or search the WordPress codex to learn how to register and enqueue JavaScript and CSS files properly.

如果您是WordPress的新手,则可以查看Younes Rafie的WordPress中排队脚本和样式 ,或搜索WordPress Codex以了解如何正确注册和排队JavaScript和CSS文件。

在每个帖子下创建“稍后再读”链接 (Creating Read Me Later Link Underneath Every Post)

Now we need to create a Read Me Later link under each blog post. By clicking the link, the user can select that post to be saved in the ‘Read Me Later’ list. After they click, the link will disappear from the post and the post ID will be saved in the database. There are two considerations when we create the link:

现在,我们需要在每个博客文章下创建一个“稍后阅读”链接。 通过单击链接,用户可以选择要保存在“以后再读”列表中的帖子。 单击后,链接将从帖子中消失,并且帖子ID将保存在数据库中。 创建链接时,有两个注意事项:

  • Only logged in user will see the link.

    只有登录的用户才能看到该链接。
  • The link will contain the ‘related’ post ID for later use.

    该链接将包含“相关”帖子ID,以供以后使用。

To achieve this, add the following function to the ReadMeLater class:

为此,请将以下函数添加到ReadMeLater类:

/**
 * Adds a read me later button at the bottom of each post excerpt that allows logged in users to save those posts in their read me later list.
 *
 * @param string $content
 * @returns string
 */
public function rml_button( $content ) {   
    // Show read me later link only when the user is logged in
    if( is_user_logged_in() && get_post_type() == post ) {
        $html .= '<a href="#" class="rml_bttn" data-id="' . get_the_id() . '">Read Me Later</a>';
        $content .= $html;
    }
    return $content;       
}

Here, we checked both if the user is logged in and if the post type is a post. After checking this we create the link. Notice that we use the HTML5 data attribute to contain the blog post’s ID which can be retrieved with the function get_the_id(). Since the link will be placed inside the post loop, this is the exact function we need.

在这里,我们检查了用户是否已登录以及帖子类型是否为帖子。 检查后,我们创建链接。 请注意,我们使用HTML5数据属性包含博客文章的ID,可以使用函数get_the_id()检索该ID。 由于链接将放置在post循环内,因此这是我们需要的确切功能。

To place the link under the each blog post, add the code bellow inside the run method:

要将链接放置在每个博客文章下,请在run方法内添加以下代码:

// Setup filter hook to show Read Me Later link
add_filter( 'the_excerpt', array( $this, 'rml_button' ) );
add_filter( 'the_content', array( $this, 'rml_button' ) );

This will filter the post excerpt and place the link inside the loop. Now when you’re logging in to your WordPress website and you browse your home page (or the page showing your posts), you’ll see the ‘Read Me Later’ link at the bottom of every post.

这将过滤后摘录并将链接放在循环内。 现在,当您登录WordPress网站并浏览主页(或显示帖子的页面)时,您将在每篇文章的底部看到“稍后再读”链接。

定义Ajax URL (Defining the Ajax URL)

When you’re going to make an Ajax call you’ll need to send the request to the admin-ajax.php file, which is a part of WordPress core. This file is responsible for handling and processing all of your Ajax requests within the WordPress context. Do NOT use the direct URL of the file path. Rather, use admin_url('admin-ajax.php') which will output the correct URL. The only problem in doing this is that you can’t put any PHP functions inside JavaScript. So we need a little trick, see the code below:

当您要进行Ajax调用时,您需要将请求发送到admin-ajax.php文件,该文件是WordPress核心的一部分。 此文件负责处理和处理WordPress上下文中的所有Ajax请求。 不要使用文件路径的直接URL。 而是使用admin_url('admin-ajax.php')将输出正确的URL。 这样做的唯一问题是您不能在JavaScript中放置任何PHP函数。 因此,我们需要一些技巧,请参见下面的代码:

wp_localize_script( 'rml-script', 'readmelater_ajax', array( 'ajax_url' => admin_url('admin-ajax.php')) );

Here, we use a function called wp_localize_script(). It takes three arguments:

在这里,我们使用一个名为wp_localize_script()函数 。 它包含三个参数:

  1. rml-script, the registration handler of the read-me-later.js script.

    rml-script ,是read-me-later.js脚本的注册处理程序。

  2. A string which will act like a JavaScript object.

    一个类似于JavaScript对象的字符串。
  3. An array which is the actual data we want to pass from our JavaScript.

    一个数组,它是我们要从JavaScript传递的实际数据。

So, if we write rml_obj.ajax_url, it will output the value of admin_url('admin-ajax.php'), in other words, the URL of the admin-ajax.php file. We’ll use it in the JavaScript part.

因此,如果我们编写rml_obj.ajax_url ,它将输出admin_url('admin-ajax.php') ,即admin-ajax.php文件的URL。 我们将在JavaScript部分中使用它。

Don’t forget to place the above code inside our enqueue_rml_scripts() method that we created earlier.

不要忘记将上面的代码放在我们enqueue_rml_scripts()创建的enqueue_rml_scripts()方法中。

添加JavaScript和您的第一个Ajax调用 (Adding JavaScript and Your First Ajax Call)

Now it’s time to create our Ajax call. Open the read-me-later.js file from our js folder. Add the below code:

现在是时候创建我们的Ajax调用了。 从我们的js文件夹中打开read-me-later.js文件。 添加以下代码:

jQuery(document).ready( function(){         
    jQuery('#content').on('click', 'a.rml_bttn', function(e) { 
        e.preventDefault();
        var rml_post_id = jQuery(this).data( 'id' );    
        jQuery.ajax({
            url : readmelater_ajax.ajax_url,
            type : 'post',
            data : {
                action : 'read_me_later',
                post_id : rml_post_id
            },
            success : function( response ) {
                jQuery('.rml_contents').html(response);
            }
        });
        jQuery(this).hide();            
    });     
});

In the above code we’ve created a function that will be called when the user clicks the ‘Read Me Later’ link. Inside this function we grab the post ID using data method and store it into the ‘rml_post_id’ variable. After that, we made our Ajax call using jQuery ‘$.ajax()’ method. This method takes several properties as we mentioned earlier in this article. Let me explain them one by one.

在上面的代码中,我们创建了一个函数,当用户单击“以后再读”链接时,该函数将被调用。 在此函数内,我们使用数据方法获取帖子ID,并将其存储到'rml_post_id'变量中。 之后,我们使用jQuery'$ .ajax()'方法进行了Ajax调用。 正如我们在本文前面提到的,此方法具有几个属性。 让我一一解释。

url contains the URL of the admin-ajax.php file. Remember how we defined rml_obj.ajax_url in the previous step? That’s how we use the URL here. Our Ajax request will be sent there for processing.

url包含admin-ajax.php文件的URL。 还记得我们在上一步中如何定义rml_obj.ajax_url吗? 这就是我们在此处使用URL的方式。 我们的Ajax请求将被发送到那里进行处理。

type indicates whether the request will send using HTTP ‘$_GET[]’ or ‘$_POST[]’ method. We use ‘$_POST[]’ method here, as we set it as post.

type表示请求将使用HTTP '$_GET[]'还是'$_POST[]'方法发送。 我们在这里使用'$_POST[]'方法,因为我们将其设置为post

data contains the data we want to send with the Ajax call. Here, our data is an object as key-value pairs. post_id contains the post ID, and action contains read_me_later which is the suffix of wp_ajax_ hook. We will define the Ajax action hook and its callback function in the next step.

data包含我们要通过Ajax调用发送的数据。 在这里,我们的数据是作为键值对的对象。 post_id包含帖子ID, action包含read_me_later ,后者是wp_ajax_ hook的后缀。 下一步,我们将定义Ajax动作钩子及其回调函数。

The last one is success which is contains an anonymous function. It will fire when the Ajax call has been finished.

最后一个是success ,它包含一个匿名函数。 当Ajax调用完成时,它将触发。

Make sure your read me later link is wrapped with a div tag with a #content id attribute otherwise the jQuery won’t work.

确保read me later链接被带有#content id属性的div标签包裹,否则jQuery将无法正常工作。

Now we need to remove the Read Me Later link right after the user clicks on it, so that the user can’t save a post twice. To achieve this, we added the following code after the jQuery.ajax() method:

现在,我们需要在用户单击后立即删除“ Read Me Later链接,以使用户无法保存帖子两次。 为此,我们在jQuery.ajax()方法之后添加了以下代码:

jQuery(this).hide();

This will remove the ‘Read Me Later’ link when the user clicks on it.

当用户单击它时,将删除“稍后阅读”链接。

阿贾克斯动作钩 (Ajax Action Hook)

Now for the important part.

现在是重要的部分。

So far we’ve created the Read Me Later link and connected it with Ajax. But the link doesn’t do anything yet, because we haven’t written any server side code to process the Ajax request. When the user clicks the link we need to save that post ID in the database and then display posts in the frontend based on the database information.

到目前为止,我们已经创建了Read Me Later链接并将其与Ajax连接。 但是该链接尚未执行任何操作,因为我们尚未编写任何服务器端代码来处理Ajax请求。 当用户单击链接时,我们需要将该帖子ID保存在数据库中,然后根据数据库信息在前端显示帖子。

To accomplish this kind of server side processing, WordPress gives us two action hooks, wp_ajax_my_action and wp_ajax_nopriv_my_action. The first one will work only for logged in users, and the second will be useful when users aren’t logged in. Because our example plugin is designed for logged in users only, we will use the first one. Note that my_action is the suffix of the wp_ajax_ hook and you can name it as you wish.

为了完成这种服务器端处理,WordPress给了我们两个动作挂钩, wp_ajax_my_actionwp_ajax_nopriv_my_action 。 第一个仅适用于已登录的用户,第二个仅在未登录用户时有用。由于我们的示例插件仅适用于已登录的用户,因此我们将使用第一个。 请注意, my_actionwp_ajax_钩子的后缀,您可以根据需要命名。

Add the following snippet inside the run() method:

run()方法内添加以下代码段:

// Setup Ajax action hook
add_action( 'wp_ajax_read_me_later', array( $this, 'read_me_later' ) );

The only thing you need to be careful of with the above code is to make sure that your Ajax hook suffix matches the value of the action property of your jQuery.ajax() method (seen in the previous step). You may notice that we give the same name to the callback function so that we can remember it easily. Now we’ll define our callback function:

上面的代码唯一需要注意的是,确保Ajax钩子后缀与jQuery.ajax()方法的action属性值匹配(在上一步中看到)。 您可能会注意到,我们对回调函数使用了相同的名称,以便我们轻松记住它。 现在,我们将定义回调函数:

public function read_me_later() {
    $rml_post_id = $_POST['post_id']; 
    $echo = array();       
    if(get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true ) !== null ) {
        $value = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
    }

    if( $value ) {
        $echo = $value;
        array_push( $echo, $rml_post_id );
    }
    else {
        $echo = array( $rml_post_id );
    }

    update_user_meta( wp_get_current_user()->ID, 'rml_post_ids', $echo );
    $ids = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
}

The above code should be placed inside our main plugin class. Let me explain what I did here.

上面的代码应该放在我们的主插件类中。 让我解释一下我在这里做了什么。

First, we stored the post ID in the $rml_post_id variable. Then we declared an empty array called $echo.

首先,我们将帖子ID存储在$rml_post_id变量中。 然后,我们声明了一个名为$echo的空数组。

After that, we check that there’s a field with the key rml_post_ids in the usermeta table in our database. If there is a row, we grab the meta value using get_user_meta() WordPress function and store it in $value.

之后,我们检查数据库中的usermeta表中是否存在一个包含键rml_post_ids的字段。 如果存在一行,我们将使用get_user_meta() WordPress函数获取元值,并将其存储在$value

Again, we check whether the $value exists or not. If true, we store it in the previously declared $echo array. Then we push the value of $rml_post_id inside the array using the array_push() function. If there is no $value, then we simply store $rml_post_id in $echo.

再次,我们检查$value是否存在。 如果为true,则将其存储在先前声明的$echo数组中。 然后,使用array_push()函数将$rml_post_id的值压入数组。 如果没有$value ,那么我们只需将$rml_post_id存储在$echo

update_user_meta() is responsible for updating (or creating, if the field has not yet been created) meta field with the data stored in $echo.

update_user_meta()负责使用存储在$echo的数据更新(或创建,如果尚未创建该字段)元字段。

Finally, we store the recently populated meta field using get_user_meta() in $ids as an array.

最后,我们使用$ids中的get_user_meta()作为数组存储最近填充的meta字段。

Now we’ve got the user chosen post IDs, we need to display those posts. Add the following code:

现在我们已经为用户选择了帖子ID,我们需要显示这些帖子。 添加以下代码:

// Query read me later posts
$args = array( 
    'post_type' => 'post',
    'orderby' => 'DESC', 
    'posts_per_page' => -1, 
    'numberposts' => -1,
    'post__in' => $ids
);

$rmlposts = get_posts( $args );
if( $ids ) :
    global $post;
    foreach ( $rmlposts as $post ) :
        setup_postdata( $post );
        $img = wp_get_attachment_image_src( get_post_thumbnail_id() ); 
    ?>          
        <div class="rml_posts">                 
            <div class="rml_post_content">
                <h5><a href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?></a></h5>
                <p><?php the_excerpt(); ?></p>
            </div>
            <img src="<?php echo $img[0]; ?>" alt="<?php echo get_the_title(); ?>" class="rml_img">                    
        </div>
    <?php 
    endforeach; 
    wp_reset_postdata(); 
endif;      

// Always die in functions echoing Ajax content
die();

Here, we use the WordPress get_posts() function to get all the posts based on the user’s choice. The only required parameter here is post__in which contains the array of post IDs. Lastly, we use die() so that our Ajax content will echo properly.

在这里,我们使用WordPress的get_posts()函数根据用户的选择获取所有帖子。 这里唯一需要的参数是post__in ,其中包含帖子ID的数组。 最后,我们使用die()以便我们的Ajax内容可以正确回显。

Here is the full code of the read_me_later() function:

这是read_me_later()函数的完整代码:

/**
 * Hook into wp_ajax_ to save post ids, then display those posts using get_posts() function
 */
public function read_me_later() {

    $rml_post_id = $_POST['post_id']; 
    $echo = array();

    if( get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true ) !== null ) {
        $value = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
    }

    if( $value ) {
        $echo = $value;
        array_push( $echo, $rml_post_id );
    }
    else {
        $echo = array( $rml_post_id );
    }

    update_user_meta( wp_get_current_user()->ID, 'rml_post_ids', $echo );
    $ids = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );

    // Query read me later posts
    $args = array( 
        'post_type' => 'post',
        'orderby' => 'DESC', 
        'posts_per_page' => -1, 
        'numberposts' => -1,
        'post__in' => $ids
    );

    $rmlposts = get_posts( $args );
    if( $ids ) :
        global $post;
        foreach ( $rmlposts as $post ) :
            setup_postdata( $post );
            $img = wp_get_attachment_image_src( get_post_thumbnail_id() ); 
        ?>          
            <div class="rml_posts">                 
                <div class="rml_post_content">
                    <h5><a href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?></a></h5>
                    <p><?php the_excerpt(); ?></p>
                </div>
                <img src="<?php echo $img[0]; ?>" alt="<?php echo get_the_title(); ?>" class="rml_img">                    
            </div>
        <?php 
        endforeach; 
        wp_reset_postdata(); 
    endif;      

    // Always die in functions echoing Ajax content
    die();

}

创建小部件以供以后阅读我的帖子 (Creating a Widget for Read Me Later Posts)

Now we need a widget to display posts saved by the user. We’ll make a very basic widget for the sake of simplicity. I’m not going to go into full detail here, we just need to extend WordPress’ WP_Widget class to create a custom widget. Let’s do it, open widget.php file and create a child class called RML_Widget that extends WP_Widget class.

现在,我们需要一个小部件来显示用户保存的帖子。 为了简单起见,我们将制作一个非常基本的小部件。 我在这里不做详细介绍,我们只需要扩展WordPress的WP_Widget类即可创建自定义小部件。 让我们来做,打开widget.php文件并创建一个名为RML_Widget的子类,该子类扩展了WP_Widget类。

class RML_Widget extends WP_Widget {}

Create the __construct() magic method inside the class to initialize our widget:

在类内部创建__construct()魔术方法以初始化我们的小部件:

function __construct() {
    parent::__construct(
       'rml_widget', // Base ID
        __( 'Read Me Later', 'text_domain' ), // Name
        array( 'classname' => 'rml_widgt', 'description' => __( 'Read Me Later widget for displaying saved posts', 'text_domain' ), ) // Args
    );
}

Here we’ve set a name and description to the widget which will display in the dashboard widget section.

在这里,我们为小部件设置了名称和说明,这些名称和说明将显示在仪表板小部件部分中。

A backend widget form will be created by the form() method, like this:

后端小部件表单将由form()方法创建,如下所示:

public function form( $instance ) {
    if ( isset( $instance['title'] ) ) {
        $title = $instance['title'];
    } else {
        $title = __( 'Read Me Later Posts', 'text_domain' );
    }
    ?>
    <p>
        <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
        <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>"
            name="<?php echo $this->get_field_name( 'title' ); ?>" type="text"
            value="<?php echo esc_attr( $title ); ?>">
        </p>
    <?php
}

As you can see, our form consists of a text field that contains the title of the widget. We assign our title in the $title variable. The get_field_id() and the get_field_name() gives our text field an unique ID and name, respectively.

如您所见,我们的表单包含一个文本字段,其中包含小部件的标题。 我们在$title变量中分配$titleget_field_id()get_field_name()为我们的文本字段提供了唯一的ID和名称。

The update() method is responsible for sanitizing and updating the user input value.

update()方法负责清理和更新用户输入值。

public function update( $new_instance, $old_instance ) {
    $instance          = array();
    $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';

    return $instance;
}

It takes two parameters:

它带有两个参数:

  1. The $new_instance contains the value entered by a user using the backend form we’ve created by the form() method.

    $new_instance包含用户使用我们通过form()方法创建的后端表单输入的值。

  2. The $old_instance is opposite, it contains the previous value.

    $old_instance相反,它包含先前的值。

Now we’ll create the widget() method which will display the ‘Read Me Later’ posts in the frontend.

现在,我们将创建widget()方法,该方法将在前端显示“稍后再读”帖子。

public function widget( $args, $instance ) {      
    $title = apply_filters( 'widget_title', $instance['title'] ); 
    echo $args['before_widget'];
    if ( ! empty( $title ) ) {
        echo $args['before_title'] . $title . $args['after_title'];
    }

    echo '<div class="rml_contents">';

        $ids = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );

        $args = array( 
            'post_type' => 'post',
            'orderby' => 'DESC', 
            'posts_per_page' => -1, 
            'numberposts' => -1,
            'post__in' => $ids
        );

        $rmlposts = get_posts( $args );
        if( $ids ) :
            global $post;
            foreach ( $rmlposts as $post ) :
                setup_postdata( $post );
                $img = wp_get_attachment_image_src( get_post_thumbnail_id() ); 
                ?>          
                <div class="rml_posts">                 
                    <div class="rml_post_content">
                        <h4><a href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?></a></h4>
                        <p><?php the_excerpt; ?></p>
                    </div>
                    <img src="<?php echo $img[0]; ?>" alt="<?php echo get_the_title(); ?>" class="rml_img">                    
                </div>
            <?php 
            endforeach;
            wp_reset_postdata();
        else :
        echo '<p>You have no saved posts now.</p>';
        endif;  

    echo '</div>';      
    echo $args['after_widget'];
}

Here we use the get_posts() function to display posts. Pretty much same as read_me_later() method.

在这里,我们使用get_posts()函数显示帖子。 与read_me_later()方法几乎相同。

Don’t forget to include the widget.php file by adding the following code at the top of the read-me-later.php file:

不要忘了包括widget.php通过在顶部加入如下代码文件read-me-later.php文件:

require(plugin_dir_path( __FILE__ ).'widget.php');

确保您的Ajax通话安全 (Making Your Ajax Calls Secure)

While working with Ajax, you should take necessary steps to make your code secure. If you’re going to receive any data from a user, sanitise it before saving it to the database. Use nonce to check if the request is coming from the correct location and made by an authenticated user. Here I’m going to show you how to use WordPress nonce in an Ajax call.

在使用Ajax时,您应该采取必要的步骤来确保代码安全。 如果要从用户接收任何数据,请先清除数据,然后再将其保存到数据库中。 使用nonce检查请求是否来自正确的位置并由经过身份验证的用户发出。 在这里,我将向您展示如何在Ajax调用中使用WordPress nonce

First, we will create a nonce using the wp_create_nonce() method and pass it from JavaScript. To achieve this, use the code from the enqueue_rml_scripts() method:

首先,我们将使用wp_create_nonce()方法创建一个随机数,并将其从JavaScript传递。 为此,请使用enqueue_rml_scripts()方法中的代码:

wp_localize_script( 'read-me-later', 'readmelater_ajax', array( 'ajax_url' => admin_url('admin-ajax.php') ) );

And replace it with the bellow code:

并将其替换为以下代码:

wp_localize_script( 'read-me-later', 'readmelater_ajax', array( 'ajax_url' => admin_url('admin-ajax.php'), 'check_nonce' => wp_create_nonce('rml-nonce') ) );

Now we can access the nonce value from our JavaScript using readmelater_ajax.check_nonce. Add a security property in the jQuery.ajax() method in your JavaScript file, like below:

现在,我们可以使用readmelater_ajax.check_nonce从JavaScript中访问随机数值。 在您JavaScript文件的jQuery.ajax()方法中添加一个安全属性,如下所示:

security : readmelater_ajax.check_nonce

Our final JavaScript will look like this:

我们的最终JavaScript如下所示:

jQuery(document).ready( function(){ 

    jQuery('#content').on('click', 'a.rml_bttn', function(e) { 
        e.preventDefault();

        var rml_post_id = jQuery(this).data( 'id' );

        jQuery.ajax({
            url : readmelater_ajax.ajax_url,
            type : 'post',
            data : {
                action : 'read_me_later',
                security : readmelater_ajax.check_nonce,               
                post_id : rml_post_id
            },
            success : function( response ) {
                jQuery('.rml_contents').html(response);
            }
        });

        jQuery(this).hide();
    }); 

});

Finally, we need to check the nonce in our Ajax callback. We will use the check_ajax_referer() function to achieve this. Add the following code at the beginning of the read_me_later() method we created earlier:

最后,我们需要检查Ajax回调中的随机数。 我们将使用check_ajax_referer()函数来实现此目的。 在我们之前创建的read_me_later()方法的开头添加以下代码:

check_ajax_referer( 'rml-nonce', 'security' );

This takes two arguments. The first is the key we created using wp_create_nonce(). The second is the security property we passed from the JavaScript.

这需要两个参数。 第一个是我们使用wp_create_nonce()创建的密钥。 第二个是我们从JavaScript传递的security属性。

If the nonce is incorrect or not set, the Ajax call will die. This way our script will block invalid Ajax requests.

如果随机数不正确或未设置,则Ajax调用将死亡。 这样,我们的脚本将阻止无效的Ajax请求。

结论 (Conclusion)

In this tutorial, we made a system where users will be able to save their favorite posts in a list and read them later. You can always add more features to it, such as creating a different page to show all saved posts, ability to add pages to the list or to add posts from custom post types for example. You can even make a dashboard settings page to configure all of the options. It’s up to you and the kind of features you want to create for your users.

在本教程中,我们创建了一个系统,用户可以在其中将自己喜欢的帖子保存在列表中,并在以后阅读。 您始终可以为其添加更多功能,例如创建一个不同的页面以显示所有已保存的帖子,可以将页面添加到列表中或从自定义帖子类型中添加帖子。 您甚至可以在仪表板设置页面上配置所有选项。 这取决于您以及要为用户创建的功能的类型。

As you can see, it’s easy to use Ajax in WordPress. It may be daunting for the first time, but once you understand how to do this, it works and looks great. WordPress Hooks are everywhere and they make your life easier. I hope you’ve picked up some useful techniques from this tutorial, now play with Ajax and make things that you love!

如您所见,在WordPress中使用Ajax很容易。 这可能是第一次令人生畏,但是一旦您了解如何做到这一点,它就会起作用并且看起来很棒。 WordPress挂钩无处不在,它们使您的生活更轻松。 希望您从本教程中学到了一些有用的技术,现在就可以玩Ajax并做自己喜欢的事情!

翻译自: https://www.sitepoint.com/how-to-use-ajax-in-wordpress-a-real-world-example/

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值