wordpress 插件_如何构建WordPress插件(第1部分)

wordpress 插件

In this tutorial, we will go through the process of creating a plugin for WordPress. A WordPress plugin extends the WordPress core and is intended to be reusable code or functionality across multiple projects. This is one of the most interesting things about it - you can share your code or functionality on the web.

在本教程中,我们将介绍为WordPress创建插件的过程。 WordPress插件扩展了WordPress核心,旨在在多个项目中实现可重用的代码或功能。 这是最有趣的事情之一-您可以在网络上共享代码或功能。

I am sure many, if not all of you, have already searched for a plugin in the WordPress repository or any of the available market places. This is one of the reasons why WordPress is so widely used. It's extremely extensible and has a huge community of developers around it. As of today, there are more than 39,000 publicly available free plugins on the WordPress repository.

我敢肯定,即使不是所有人,很多人已经在WordPress资料库或任何可用的市场中搜索了插件。 这就是WordPress如此广泛使用的原因之一。 它具有极好的可扩展性,并且周围有大量的开发人员社区。 截止到今天, WordPress信息库中已经有超过39,000个公开可用的免费插件。

我为什么要打扰做一个插件? (Why should I bother making a plugin?)

The plugin we are going to make in this tutorial will help automate some of the most usual functions developers do when creating a new WordPress project. By the end of this tutorial you will know how to:

我们将在本教程中制作插件将帮助自动化开发人员在创建新的WordPress项目时执行的一些最常用的功能。 在本教程结束时,您将知道如何:

  • Setup a basic WordPress plugin page

    设置基本的WordPress插件页面
  • Create custom input fields on that plugin page

    在该插件页面上创建自定义输入字段
  • Validate those input fields

    验证那些输入字段

You might be thinking that it would be easier and faster to just copy and paste code from your last project and not to even bother with writing a custom plugin to do this. Well, this is where you are wrong!

您可能会认为,仅复制和粘贴上一个项目中的代码会更轻松,更快捷,而不必费心编写一个自定义插件来执行此操作。 好吧,这就是你错了!

This example will demonstrate the benefits of a WordPress plugin's purpose by eliminating repetition. All you'll need to do is add your plugin, change the options, and be on your way. You won't need to worry that you forgot a function or anything because it's all self-contained to a single plugin.

本示例将通过消除重复来演示WordPress插件的目的所带来的好处。 您需要做的就是添加插件,更改选项,然后按自己的方式进行。 您无需担心会忘记一个函数或任何东西,因为它们全都包含在单个插件中。

The best part about building a WordPress plugin is joining the WordPress open-source community. You can share and get feedback on your work, sell it as a premium plugin, and add it to a browsable marketplace.

关于构建WordPress插件的最佳部分是加入WordPress开源社区。 您可以分享并获得有关您工作的反馈,可以将其作为高级插件出售,然后将其添加到可浏览的市场中。

入门 (Getting Started)

wp-cleanup-what-we-are-doing

Above is a screenshot of the final plugin we're building. As mentioned earlier, it groups a handful of functions and settings you would usually add to each new project.

上面是我们正在构建的最终插件的屏幕截图。 如前所述,它将通常添加到每个新项目中的少数功能和设置归为一组。

Some of cool things that we're going to be able to do are:

我们将要做的一些很酷的事情是:

  • Dynamically add new images sizes

    动态添加新图像尺寸
  • Customize the login page

    自定义登录页面
  • Optionally clean up the head section

    (可选)清理头部
  • Optionally remove injected CSS for the comment widget

    (可选)删除为注释小部件注入CSS
  • Optionally remove injected CSS for galleries

    (可选)删除画廊的注入CSS
  • Optionally add a Post slug to the body class

    (可选)将Post slug添加到body类
  • Optionally load jQuery from a CDN

    (可选)从CDN加载jQuery
  • And many other useful options

    和许多其他有用的选项

The best way to begin with a new plugin is by working on the incredibly useful WordPress Plugin Boilerplate. You might ask yourself why you would use a boilerplate instead of building from scratch. This boilerplate will get you started quick with a standardized, organized and object-oriented foundation - basically everything you want if you started from scratch.

开始使用新插件的最佳方法是研究非常有用的WordPress插件模板 。 您可能会问自己,为什么要使用样板而不是从头开始构建。 该样板将帮助您快速建立一个标准化,组织化和面向对象的基础-如果您从头开始,基本上就是您想要的一切。

To get started, just go to the WordPress Plugin Boilerplate Generator and fill-out the form and click on the Build button.

首先,只需转到WordPress插件样板生成器并填写表格,然后单击“ 生成”按钮。

boilerplate-genrator-form

You now have just downloaded the generated plugin boilerplate as a .zip file. Now, simply unzip it and add it to your WordPress development installation in the plugins folder.

现在,您刚刚将生成的插件样板下载为.zip文件。 现在,只需将其解压缩并将其添加到plugins文件夹中的WordPress开发安装中即可。

You might want to have a dedicated local environment for testing your plugins. We recommend using either MAMP/XAMP or using a LAMP vagrant box like the awesome Scotch Box. You should also make sure to turn on the debug functionalities of WordPress by adding the following to your wp-config.php file:

您可能需要一个专用的本地环境来测试您的插件。 我们建议您使用MAMP / XAMP或使用LAMP流浪者盒子,例如超棒的Scotch Box 。 您还应该确保通过将以下内容添加到wp-config.php文件中来打开WordPress的调试功能:

define('WP_DEBUG', true)

This will help us check for any errors while coding our plugin.

这将有助于我们在编码插件时检查是否有任何错误。

插件样板文件夹结构 (Plugin Boilerplate Folder Structure)

Now that the boilerplate of our plugin is ready and installed, let's review a bit about the plugin folder structure before we begin with coding it.

既然我们的插件样板已经准备好并已安装,那么在开始对其进行编码之前,让我们先回顾一下有关插件文件夹结构的信息。

folder-structure-sublime

First thing you might notice, is that we have 4 main folders:

您可能会注意到的第一件事是,我们有4个主要文件夹:

管理员 (Admin)

The folder admin is where all our admin facing code will live; including CSS, JS and partials folders and our PHP admin class file class-wp-cbf-admin.php.

文件夹admin是我们所有面向管理员的代码所在的位置; 包括CSS,JS和partials文件夹,以及我们PHP管理类文件class-wp-cbf-admin.php

包括 (Includes)

Here you will find:

在这里您会发现:

  • The main plugin PHP class class-wp-cbf.php where we will add all our actions and filters.

    主插件PHP类class-wp-cbf.php ,我们将在其中添加所有操作和过滤器。
  • The activator file class-wp-cbf-activator.php.

    激活文件class-wp-cbf-activator.php
  • The deactivator file class-wp-cbf-desactivator.php, the internationalization file class-wp-cbf-i18n.php

    停用文件class-wp-cbf-desactivator.php class-wp-cbf-i18n.php ,国际化文件class-wp-cbf-i18n.php
  • The loader file class-wp-cbf-loader.php which will basically call all our actions in the main class file.

    加载程序文件class-wp-cbf-loader.php基本上将调用主类文件中的所有操作。
  • The languages folder which is a ready to use .pot file to make your plugin in muliple languages.

    languages文件夹可以随时使用.pot文件来制作多种语言的插件。
  • The public folder is the same as our admin folder except for public facing functionalities.

    public文件夹相同,我们的admin除了面向公众的功能文件夹。

This leaves us with 4 files:

这给我们留下了4个文件:

  • LICENCE.txt: GPL-2 license.

    LICENCE.txt :GPL-2许可证。
  • README.txt: This will include your plugin name, compatibility version, and description as seen on the plugin page in the WordPress repository. This is the first file we will edit.

    README.txt :这将包括您的插件名称,兼容性版本和描述,如WordPress存储库中的插件页面所示。 这是我们将编辑的第一个文件。
  • uninstall.php: This script is called when the user clicks on the Delete link in the WordPress plugin backend.

    uninstall.php :当用户单击WordPress插件后端中的Delete链接时,将调用此脚本。
  • wp-cbf.php: This is the main plugin bootstrap file. You will likely edit this file with the version number and the short description of your plugin.

    wp-cbf.php :这是主要的插件引导文件。 您可能会使用插件的版本号和简短描述来编辑此文件。

Now that all this is cleared, it's time to get our hands dirty. Let's add some code to our brand new plugin!

现在已经清除了所有这些内容,现在该弄脏我们的手了。 让我们向我们全新的插件中添加一些代码!

初始化并添加设置页面 (Initialize and Add a Setting Page)

plugins-admin-first

If you go to the plugins page in your WordPress back-end, you will see our plugin with its title, a description, and Activate, Edit and Delete links.

如果您转到WordPress后端中的插件页面,您将看到我们的插件及其标题,说明以及“ Activate ,“ Edit和“ Delete链接。

If you click on Activate, it will work thanks to the activator and deactivator classes in the includes folder. This is great, but once activated, nothing really will happen yet.

如果单击Activate ,则由于includes文件夹中的activatordeactivator类,它可以工作。 很好,但是一旦激活,什么都不会发生。

We need to add a settings page where we will add our plugin options. You might also notice here that we still have a very generic description - let's fix that first.

我们需要添加一个设置页面,在其中添加插件选项。 您可能还会在这里注意到,我们仍然有一个非常笼统的描述-让我们首先修复它。

This short description is written in the comments of the main plugin class: wp-cbf/wp-cbf.php

此简短描述写在主插件类的注释中: wp-cbf/wp-cbf.php

short-description

Since we are at the root of our plugin, let's update the README.txt file. You will want this to be pretty detailed explanation, especially since this is what people will see when they reach your plugin webpage. You'll also notice installation and FAQ sections. The more you cover here, the less you might need to explain during possible support later.

由于我们是插件的根目录,因此让我们更新README.txt文件。 您会希望这是非常详细的说明,尤其是因为这是人们在您访问插件网页时会看到的内容。 您还会注意到安装和常见问题解答部分。 您在此处涵盖的内容越多,在以后的支持期间您可能需要解释的内容就越少。

If you reload your Plugins admin page now, you will see your new description.

如果您现在重新加载插件管理页面,将会看到新的描述。

plugin-with-short-desc

Next, let's add a setting page so we will be able to edit our plugin's options.

接下来,让我们添加一个设置页面,以便我们能够编辑插件的选项。

Open the admin/class-wp-cbf-admin.php where we have 3 functions already here:

打开admin/class-wp-cbf-admin.php ,我们这里已有3个功能:

  • __construct which is instantiated whenever this class is called

    __construct ,每当调用此类时实例化
  • And 2 enqueueing functions: enqueue_styles and enqueue_scripts which are used where we will add our admin related CSS and JS

    还有2个入队功能: enqueue_stylesenqueue_scripts ,用于在其中添加与管理员相关CSS和JS

After these functions, add these following 3 functions. You don't need to add the huge comment blocks since they're just there to help you.

在这些功能之后,添加以下三个功能。 您不需要添加巨大的注释块,因为它们可以帮助您。

/**
*
* admin/class-wp-cbf-admin.php - Don't add this
*
**/

/**
 * Register the administration menu for this plugin into the WordPress Dashboard menu.
 *
 * @since    1.0.0
 */

public function add_plugin_admin_menu() {

    /*
     * Add a settings page for this plugin to the Settings menu.
     *
     * NOTE:  Alternative menu locations are available via WordPress administration menu functions.
     *
     *        Administration Menus: http://codex.wordpress.org/Administration_Menus
     *
     */
    add_options_page( 'WP Cleanup and Base Options Functions Setup', 'WP Cleanup', 'manage_options', $this->plugin_name, array($this, 'display_plugin_setup_page')
    );
}

 /**
 * Add settings action link to the plugins page.
 *
 * @since    1.0.0
 */

public function add_action_links( $links ) {
    /*
    *  Documentation : https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)
    */
   $settings_link = array(
    '<a href="' . admin_url( 'options-general.php?page=' . $this->plugin_name ) . '">' . __('Settings', $this->plugin_name) . '</a>',
   );
   return array_merge(  $settings_link, $links );

}

/**
 * Render the settings page for this plugin.
 *
 * @since    1.0.0
 */

public function display_plugin_setup_page() {
    include_once( 'partials/wp-cbf-admin-display.php' );
}

Let's review and explain those 3 functions:

让我们回顾并解释这三个功能:

add_plugin_admin_menu() (add_plugin_admin_menu())

add_plugin_admin_menu(), as its name says, will add a menu item in the Settings sub-menu items. This is called by the add_options_page(). This function takes five arguments:

add_plugin_admin_menu()add_plugin_admin_menu()将在“ Settings子菜单项中添加一个菜单项。 这由add_options_page()调用。 该函数有五个参数:

  • The page title: Here 'WP Cleanup and Base Options Functions Setup'.

    页面标题 :此处为“ WP清理和基本选项功能设置”。
  • The menu title: Here 'WP Cleanup' as you might want to keep it small to span on just one line.

    菜单标题 :此处为“ WP Cleanup”,您可能希望将其保持较小尺寸以仅跨越一行。
  • Capabilities: Who will be able to access this menu item (Admin, Editor, etc..).

    功能 :谁将能够访问此菜单项(管理员,编辑器等)。
  • The menu slug: Here as for mostly everything we will reference in this plugin we will use the plugin short name (we will access it with $this->plugin_name).

    菜单slug :这里几乎所有我们将在此插件中引用的内容都将使用插件的简称(我们将使用$ this-> plugin_name对其进行访问)。
  • The callback function: If you look closely here, we are calling our 3rd function display_plugin_setup_page(). This is where our options will be displayed.

    回调函数 :如果您仔细看这里,我们将调用第三个函数display_plugin_setup_page() 。 这是显示我们的选项的地方。

add_action_links() (add_action_links())

This function adds a "Settings" link to the "Deactivate | Edit" list when our plugin is activated. It takes one argument, the $links array to which we will merge our new link array.

当我们的插件被激活时,此功能将“设置”链接添加到“停用|编辑”列表。 它使用一个参数,即$links数组,我们将新的link数组合并到该数组中。

display_plugin_setup_page() (display_plugin_setup_page())

This one is called inside our first add_plugin_admin_menu() function. It just includes the partial file where we will add our Options. It will be mostly HTML and some little PHP logic.

在我们的第一个add_plugin_admin_menu()函数中调用此函数。 它仅包括部分文件,我们将在其中添加选项。 它主要是HTML和一些PHP逻辑。

All this is great, but if you just save that file and go back to your plugin page, nothing new will appear yet. We first need to register these functions into your define_admin_hook.

所有这些都很棒,但是如果您只保存该文件并返回到插件页面,则不会出现任何新内容。 我们首先需要将这些函数注册到您的define_admin_hook

Go to the includes folder and open includes/class-wp-cbf.php. We need to add the following define_admin_hooks() private function to get this started:

转到includes文件夹并打开includes/class-wp-cbf.php 。 我们需要添加以下define_admin_hooks()私有函数来开始此操作:

/**
*
* include/class-wp-cbf.php - Don't add this
*
**/

// Add menu item
$this->loader->add_action( 'admin_menu', $plugin_admin, 'add_plugin_admin_menu' );

// Add Settings link to the plugin
$plugin_basename = plugin_basename( plugin_dir_path( __DIR__ ) . $this->plugin_name . '.php' );
$this->loader->add_filter( 'plugin_action_links_' . $plugin_basename, $plugin_admin, 'add_action_links' );

Each one of these lines are calling the loader file, actions, or filter hooks. From the includes/wp-cbf-loader.php file, we can get the way we have to add our arguments for example for the first action:

这些行中的每一行都在调用加载程序文件,操作或过滤器挂钩。 从includes/wp-cbf-loader.php文件中,我们可以了解必须为第一个操作添加参数的方式:

  • $hook ('admin_menu'), this is the action/filter hook we will add our modifications to

    $hook ('admin_menu'),这是动作/过滤器挂钩,我们将对其进行修改
  • $component ($plugin_admin), this is a reference to the instance of the object on which the action is defined, more simply, if we had a hook to the admin_hooks it will be $plugin_admin on the public hooks it will be $plugin_public

    $component ($ plugin_admin),这是对在其上定义了操作的对象实例的引用,更简单地说,如果我们对admin_hooks有一个钩子,则在公共钩子上将是$ plugin_admin,它将是$ plugin_public
  • $callback (add_plugin_admin_menu), the name of our function

    $callback (add_plugin_admin_menu),我们函数的名称
  • $priority (not set here - default is 10), priority at which the function is fired with the default being 10

    $priority (此处未设置-默认为10),该函数被触发时的优先级,默认为10
  • $accepted_args (not set here - default is 1), number of arguments passed to our callback function

    $accepted_args (此处未设置-默认为1),传递给我们的回调函数的参数数量

You can also see that we are setting up a $plugin_basename variable. It will give us the plugin main class file and is needed to add the action_links.

您还可以看到我们正在设置$plugin_basename变量。 它将为我们提供插件主类文件,并且需要添加action_links

Now, if you refresh your plugins admin page and activate the plugin you will now see the "Settings" link and also the menu link in there.

现在,如果刷新插件管理页面并激活插件,您现在将在其中看到“设置”链接以及菜单链接。

menu_links_added

添加自定义输入字段 (Adding Custom Input Fields)

Now we have a page to display our settings and that's pretty good, but it's empty. You can verify that by jumping on this page by either clicking on the "Settings" link on the "WP Cleanup" menu item.

现在我们有了一个页面来显示我们的设置,这很好,但是它是空的。 您可以通过单击“ WP Cleanup”菜单项上的“ Settings”链接来跳至此页面来验证。

Before you go and add all your options fields, you might want to write all your plugin options on paper with the type of field you will add. For this particular plugin, most of these will be checkboxes to enable/disable functionalities, a couple of text inputs, selects that we will cover below, and some other very specific fields (color-pickers and image uploads that we will talk about in part 2.

在添加所有选项字段之前,您可能希望将要添加的字段类型写在纸上的所有插件选项上。 对于这个特定的插件,大多数将是用于启用/禁用功能的复选框,几个文本输入,我们将在下面介绍的选择以及一些其他非常具体的字段(颜色选择器和图像上传,我们将在下面进行部分讨论) 2。

I would also recommend using another utility plugin to grab all the admin-specific markup that we will use. It's not available on the WordPress repository, so you will need to get it from GitHub: WordPress Admin Style

我还建议使用另一个实用程序插件来获取我们将要使用的所有特定于管理员的标记。 它在WordPress存储库中不可用,因此您需要从GitHub获取它: WordPress Admin Style

wp-admin-style

Now, with our list of fields and some admin related markup, we can go on and add our first inputs. For our plugin's purpose, we will be adding 4 checkboxes to start.

现在,使用字段列表和一些与管理员相关的标记,我们可以继续添加第一个输入。 出于插件的目的,我们将添加4个复选框开始。

Open admin/partials/wp-cbf-admin-display.php since it's the file that will display our settings page (as stated in our add_options_page()). Now add the following:

打开admin/partials/wp-cbf-admin-display.php因为它是显示我们设置页面的文件(如我们的add_options_page() )。 现在添加以下内容:

<?php
/**
*
* admin/partials/wp-cbf-admin-display.php - Don't add this comment
*
**/
?>

<!-- This file should primarily consist of HTML with a little bit of PHP. -->
<div class="wrap">

    <h2><?php echo esc_html(get_admin_page_title()); ?></h2>

    <form method="post" name="cleanup_options" action="options.php">

        <!-- remove some meta and generators from the <head> -->
        <fieldset>
            <legend class="screen-reader-text"><span>Clean WordPress head section</span></legend>
            <label for="<?php echo $this->plugin_name; ?>-cleanup">
                <input type="checkbox" id="<?php echo $this->plugin_name; ?>-cleanup" name="<?php echo $this->plugin_name; ?> [cleanup]" value="1"/>
                <span><?php esc_attr_e('Clean up the head section', $this->plugin_name); ?></span>
            </label>
        </fieldset>

        <!-- remove injected CSS from comments widgets -->
        <fieldset>
            <legend class="screen-reader-text"><span>Remove Injected CSS for comment widget</span></legend>
            <label for="<?php echo $this->plugin_name; ?>-comments_css_cleanup">
                <input type="checkbox" id="<?php echo $this->plugin_name; ?>-comments_css_cleanup" name="<?php echo $this->plugin_name; ?>[comments_css_cleanup]" value="1"/>
                <span><?php esc_attr_e('Remove Injected CSS for comment widget', $this->plugin_name); ?></span>
            </label>
        </fieldset>

        <!-- remove injected CSS from gallery -->
        <fieldset>
            <legend class="screen-reader-text"><span>Remove Injected CSS for galleries</span></legend>
            <label for="<?php echo $this->plugin_name; ?>-gallery_css_cleanup">
                <input type="checkbox" id="<?php echo $this->plugin_name; ?>-gallery_css_cleanup" name="<?php echo $this->plugin_name; ?>[gallery_css_cleanup]" value="1" />
                <span><?php esc_attr_e('Remove Injected CSS for galleries', $this->plugin_name); ?></span>
            </label>
        </fieldset>

        <!-- add post,page or product slug class to body class -->
        <fieldset>
            <legend class="screen-reader-text"><span><?php _e('Add Post, page or product slug to body class', $this->plugin_name); ?></span></legend>
            <label for="<?php echo $this->plugin_name; ?>-body_class_slug">
                <input type="checkbox" id="<?php echo $this->plugin_name;?>-body_class_slug" name="<?php echo $this->plugin_name; ?>[body_class_slug]" value="1" />
                <span><?php esc_attr_e('Add Post slug to body class', $this->plugin_name); ?></span>
            </label>
        </fieldset>

        <!-- load jQuery from CDN -->
        <fieldset>
            <legend class="screen-reader-text"><span><?php _e('Load jQuery from CDN instead of the basic wordpress script', $this->plugin_name); ?></span></legend>
            <label for="<?php echo $this->plugin_name; ?>-jquery_cdn">
                <input type="checkbox"  id="<?php echo $this->plugin_name; ?>-jquery_cdn" name="<?php echo $this->plugin_name; ?>[jquery_cdn]" value="1" />
                <span><?php esc_attr_e('Load jQuery from CDN', $this->plugin_name); ?></span>
            </label>
                    <fieldset>
                        <p>You can choose your own cdn provider and jQuery version(default will be Google Cdn and version 1.11.1)-Recommended CDN are <a href="https://cdnjs.com/libraries/jquery">CDNjs</a>, <a href="https://code.jquery.com/jquery/">jQuery official CDN</a>, <a href="https://developers.google.com/speed/libraries/#jquery">Google CDN</a> and <a href="http://www.asp.net/ajax/cdn#jQuery_Releases_on_the_CDN_0">Microsoft CDN</a></p>
                        <legend class="screen-reader-text"><span><?php _e('Choose your prefered cdn provider', $this->plugin_name); ?></span></legend>
                        <input type="url" class="regular-text" id="<?php echo $this->plugin_name; ?>-cdn_provider" name="<?php echo $this->plugin_name; ?>[cdn_provider]" value=""/>
                    </fieldset>
        </fieldset>

        <?php submit_button('Save all changes', 'primary','submit', TRUE); ?>

    </form>

</div>

Nothing should be very surprising here - it's just a basic form and a couple of checkboxes.

在这里没有什么奇怪的-它只是一个基本形式和几个复选框。

first-fields-added

I you try to check one of these checkboxes now and hit save, you will get redirected to the options.php page. This is because if you look at our form, the action attribute is linked to options.php. So let's go on and save those options.

我现在尝试检查其中一个复选框并点击保存,您将被重定向到options.php页面。 这是因为,如果您查看我们的表单,则action属性链接到options.php 。 因此,让我们继续保存这些选项。

At this point, you might be thinking that before saving any of these options, that we should probably be first validating and sanitizing them. Well that's exaclty what we're going to do.

在这一点上,您可能会认为,在保存任何这些选项之前,我们可能应该首先对其进行验证和消毒。 好吧,这是我们要做的。

So let's validate and sanitize those options:

因此,让我们验证并清除这些选项:

Let's open admin/class-wp-cbf.php in our editor and add a new validation function. So after our display_plugin_setup_page() function jump a couple of lines and add the following:

让我们在编辑器中打开admin/class-wp-cbf.php并添加一个新的验证功能。 因此,在我们的display_plugin_setup_page()函数之后,跳转了几行并添加了以下内容:

/**
*
* admin/class-wp-cbf-admin.php
*
**/
public function validate($input) {
    // All checkboxes inputs        
    $valid = array();

    //Cleanup
    $valid['cleanup'] = (isset($input['cleanup']) && !empty($input['cleanup'])) ? 1 : 0;
    $valid['comments_css_cleanup'] = (isset($input['comments_css_cleanup']) && !empty($input['comments_css_cleanup'])) ? 1: 0;
    $valid['gallery_css_cleanup'] = (isset($input['gallery_css_cleanup']) && !empty($input['gallery_css_cleanup'])) ? 1 : 0;
    $valid['body_class_slug'] = (isset($input['body_class_slug']) && !empty($input['body_class_slug'])) ? 1 : 0;
    $valid['jquery_cdn'] = (isset($input['jquery_cdn']) && !empty($input['jquery_cdn'])) ? 1 : 0;
    $valid['cdn_provider'] = esc_url($input['cdn_provider']);

    return $valid;
 }

As you can see here, we just created a function called validate, and we are passing it an $input argument. We then add some logic for the checkboxes to see if the input is valid.

如您在这里看到的,我们刚刚创建了一个名为validate的函数,并且正在向它传递一个$input参数。 然后,我们为复选框添加一些逻辑,以查看输入是否有效。

We're doing this with isset and !empty which checks for us if the checkbox as been checked or not. It will assign the valid[] array the value we get from that verification. We also checked our url input field with the esc_url for a simple text field. We used a sanitize_text_field instead, but the process is the same.

我们使用isset!empty来执行此操作,这将检查我们是否选中了该复选框。 它将为valid[]数组分配从该验证中获得的值。 我们还使用esc_url检查了url输入字段中的简单文本字段。 我们改用sanitize_text_field ,但过程相同。

We are now going to add the saving/update function for our options.

现在,我们将为选项添加保存/更新功能。

In the same file, right before the previous code, add:

在同一文件中,紧接在前面的代码之前,添加:

/**
*
* admin/class-wp-cbf-admin.php
*
**/
 public function options_update() {
    register_setting($this->plugin_name, $this->plugin_name, array($this, 'validate'));
 }

Here we use the register_setting() function which is part of the WordPress API. We are passing it three arguments:

在这里,我们使用register_setting()函数,该函数是WordPress API的一部分。 我们为其传递了三个参数:

  • Our option group: Here we will use our $plugin_name as it's unique and safe.

    我们的选项组 :在这里,我们将使用我们的$plugin_name因为它是唯一且安全的。
  • Option name: You can register each option as a single, We will save all our options at once - so we will use the $plugin_name again.

    选项名称 :您可以将每个选项注册为一个,我们将立即保存所有选项-因此我们将再次使用$plugin_name
  • A callback function: This is used to sanitize our options with the validation function we just created.

    回调函数 :用于通过刚刚创建的验证函数对选项进行清理。

Now that we have registered our settings, we need to add a small line of php to our form in order to get it working properly. This line will add a nonce, option_page, action, and a http_referer field as hidden inputs.

现在我们已经注册了设置,我们需要在表单中添加一小段php,以使其正常工作。 该行将添加一个nonceoption_pageaction和一个http_referer字段作为隐藏输入。

So open up the form and update it so it look like the below code:

因此,打开表单并更新它,使其看起来像下面的代码:

<?php
/**
*
* admin/partials/wp-cbf-admin-display.php - Don't add this comment
*
**/
?>

<div class="wrap">

    <h2><?php echo esc_html( get_admin_page_title() ); ?></h2>

    <form method="post" name="cleanup_options" action="options.php">

    <?php settings_fields($this->plugin_name); ?>

    <!-- This file should primarily consist of HTML with a little bit of PHP. -->

    ...

Great - we are almost there! We're just missing one last step. We need to register the options_update() to the admin_init hook.

太好了-我们快到了! 我们只是缺少最后一步。 我们需要将options_update()注册到admin_init挂钩。

Open includes/class-wp-cbf.php and register our new action:

打开includes/class-wp-cbf.php并注册我们的新操作:

/**
*
* include/class-wp-cbf.php
*
**/

// Save/Update our plugin options
$this->loader->add_action('admin_init', $plugin_admin, 'options_update');

Let's try our option page now. On save, the page should refresh, and you should see a notice saying "Settings saved".

让我们现在尝试我们的选项页面。 保存后,页面应该刷新,并且您应该看到一条提示“设置已保存”的通知。

settings-saved

Victory is ours!

胜利是我们的!

But wait... If you had a checkbox checked, it's no longer showing as checked now...

但是,请稍等...如果您选中了一个复选框,那么该复选框将不再显示为选中状态...

It because we now just need to grab our "options" values and add a small condition to our inputs to reflect this.

这是因为我们现在只需要获取“选项”值,并在输入中添加一个小的条件即可反映这一点。

Open again the admin/partials/wp-cbf-admin.php file and update it as follow

再次打开admin/partials/wp-cbf-admin.php文件,并按照以下说明进行更新

<h2 class="nav-tab-wrapper">Clean up</h2>

    <form method="post" name="cleanup_options" action="options.php">

    <?php
        //Grab all options
        $options = get_option($this->plugin_name);

        // Cleanup
        $cleanup = $options['cleanup'];
        $comments_css_cleanup = $options['comments_css_cleanup'];
        $gallery_css_cleanup = $options['gallery_css_cleanup'];
        $body_class_slug = $options['body_class_slug'];
        $jquery_cdn = $options['jquery_cdn'];
        $cdn_provider = $options['cdn_provider'];
    ?>

    <?php
        settings_fields($this->plugin_name);
        do_settings_sections($this->plugin_name);
    ?>

    <!-- remove some meta and generators from the <head> -->
    <fieldset>
        <legend class="screen-reader-text">
            <span>Clean WordPress head section</span>
        </legend>
        <label for="<?php echo $this->plugin_name; ?>-cleanup">
            <input type="checkbox" id="<?php echo $this->plugin_name; ?>-cleanup" name="<?php echo $this->plugin_name; ?>[cleanup]" value="1" <?php checked($cleanup, 1); ?> />
            <span><?php esc_attr_e('Clean up the head section', $this->plugin_name); ?></span>
        </label>
    </fieldset>

    <!-- remove injected CSS from comments widgets -->
    <fieldset>
        <legend class="screen-reader-text"><span>Remove Injected CSS for comment widget</span></legend>
        <label for="<?php echo $this->plugin_name; ?>-comments_css_cleanup">
            <input type="checkbox" id="<?php echo $this->plugin_name; ?>-comments_css_cleanup" name="<?php echo $this->plugin_name; ?>[comments_css_cleanup]" value="1" <?php checked($comments_css_cleanup, 1); ?> />
            <span><?php esc_attr_e('Remove Injected CSS for comment widget', $this->plugin_name); ?></span>
        </label>
    </fieldset>

    <!-- remove injected CSS from gallery -->
    <fieldset>
        <legend class="screen-reader-text"><span>Remove Injected CSS for galleries</span></legend>
        <label for="<?php echo $this->plugin_name; ?>-gallery_css_cleanup">
            <input type="checkbox" id="<?php echo $this->plugin_name; ?>-gallery_css_cleanup" name="<?php echo $this->plugin_name; ?>[gallery_css_cleanup]" value="1" <?php checked( $gallery_css_cleanup, 1 ); ?>  />
            <span><?php esc_attr_e('Remove Injected CSS for galleries', $this->plugin_name); ?></span>
        </label>
    </fieldset>

    <!-- add post,page or product slug class to body class -->
    <fieldset>
        <legend class="screen-reader-text"><span><?php _e('Add Post, page or product slug to body class', $this->plugin_name); ?></span></legend>
        <label for="<?php echo $this->plugin_name; ?>-body_class_slug">
            <input type="checkbox" id="<?php echo $this->plugin_name; ?>-body_class_slug" name="<?php echo $this->plugin_name; ?>[body_class_slug]" value="1" <?php checked($body_class_slug, 1); ?>  />
            <span><?php esc_attr_e('Add Post slug to body class', $this->plugin_name); ?></span>
        </label>
    </fieldset>

    <!-- load jQuery from CDN -->
    <fieldset>
        <legend class="screen-reader-text"><span><?php _e('Load jQuery from CDN instead of the basic wordpress script', $this->plugin_name); ?></span></legend>
        <label for="<?php echo $this->plugin_name; ?>-jquery_cdn">
            <input type="checkbox"  id="<?php echo $this->plugin_name; ?>-jquery_cdn" name="<?php echo $this->plugin_name; ?>[jquery_cdn]" value="1" <?php checked($jquery_cdn,1); ?>/>
            <span><?php esc_attr_e('Load jQuery from CDN', $this->plugin_name); ?></span>
        </label>
        <fieldset>
            <p>You can choose your own cdn provider and jQuery version(default will be Google Cdn and version 1.11.1)-Recommended CDN are <a href="https://cdnjs.com/libraries/jquery">CDNjs</a>, <a href="https://code.jquery.com/jquery/">jQuery official CDN</a>, <a href="https://developers.google.com/speed/libraries/#jquery">Google CDN</a> and <a href="http://www.asp.net/ajax/cdn#jQuery_Releases_on_the_CDN_0">Microsoft CDN</a></p>
            <legend class="screen-reader-text"><span><?php _e('Choose your prefered cdn provider', $this->plugin_name); ?></span></legend>
            <input type="url" class="regular-text" id="<?php echo $this->plugin_name; ?>-cdn_provider" name="<?php echo $this->plugin_name; ?>[cdn_provider]" value="<?php if(!empty($cdn_provider)) echo $cdn_provider; ?>"/>
        </fieldset>
    </fieldset>

    <?php submit_button('Save all changes', 'primary','submit', TRUE); ?>

So what we're doing is basically checking to see if the value exists already, and, if it does, populating the input field with the current value.

因此,我们要做的基本上是检查该值是否已经存在,如果存在,则使用当前值填充输入字段。

We do this by first grabbing all our options and assigning each one to a variable (try to keep those explicit so you know which is which).

为此,我们首先获取所有选项,然后将每个选项分配给一个变量(尝试使它们保持显式,以便您知道哪个是哪个)。

Then we add a small condition. We will use the WordPress built-in checked function on our inputs to get the saved value and add the "checked" attribute if the option exists and is set to 1.

然后我们添加一个小条件。 我们将在输入中使用WordPress内置checked功能来获取保存的值,并在选项存在且设置为1的情况下添加“ checked”属性。

So save your file, try to save your plugin once last time, and, boom!, we have successfully finished our plugin.

因此,请保存文件,最后一次尝试保存一次插件,然后繁荣发展! ,我们已经成功完成了插件。

settings-saved-success

这是第一部分的内容 (That's a wrap for part 1)

We have seen a lots of things. From the benefits of creating your own plugin and sharing it with fellow WordPress users to why you might want to make your repetitive functions into a plugin. We have reviewed the incredible WordPress Plugin Boilerplate, its structure, and why you should definitely use it.

我们已经看到了很多东西。 从创建自己的插件并将其与其他WordPress用户共享的好处到为什么您可能要将重复的功能纳入插件的原因。 我们已经审查了令人难以置信的WordPress插件样板 ,其结构以及为什么一定要使用它。

We put our hands in the grease and pushed ourselves in the first steps of doing a plugin, with 2 types of fields validation and sanitization, all that keeping a Oriented Object PHP process with clean and explicit code. We're not finished yet though.

我们投入了很多精力,并在开发插件的第一步中投入了自己的精力,它具有两种类型的字段验证和消毒处理,所有这些都使Oriented Object PHP流程保持简洁明了的代码。 我们还没有完成。

In part 2, we will make our plugin alive, creating the functions that will actually influence your WordPress website, we will also discover more complex field types and sanitization, and, finally, get our plugin ready to be reviewed by the WordPress repository team.

在第2部分中,我们将使我们的插件生效,创建实际上会影响您的WordPress网站的功能,我们还将发现更复杂的字段类型和清理操作,最后使我们的插件准备好供WordPress存储库团队审查。

We'll wrap this up with some additional links and sources:

我们将通过一些其他链接和源进行总结:

翻译自: https://scotch.io/tutorials/how-to-build-a-wordpress-plugin-part-1

wordpress 插件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值