Brad Williams - Professional WordPress Plugin Development

Здесь есть возможность читать онлайн «Brad Williams - Professional WordPress Plugin Development» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Professional WordPress Plugin Development: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Professional WordPress Plugin Development»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Extend WordPress with plugins using this advanced WordPress development book, updated for the current version This significantly updated edition of
addresses modern plugin development for WordPress, the highly popular content management system (CMS). If you’re using WordPress to create and manage websites, WordPress plugins are the software that can extend or enhance CMS functionality. This book offers guidance on writing plugins for WordPress sites to share or sell to other users.
The second edition of
covers the building of advanced plugin development scenarios. It discusses the plugin framework and coding standards as well as dashboards, settings, menus, and related application programming interfaces (APIs). Additional topics include security, performance, data validation, and SQL statements.
• Learn about the power of hooks in WordPress
• Discover how JavaScript and Ajax will work in your site
• Understand key technologies: Block Editor/Gutenberg, JS/React, PHP, and the REST API
• Create and use custom post types and taxonomies.
• Creating custom dashboard menus and plugin settings
• Work with users and user data
• Schedule tasks and utilizing Cron
• Performance and security considerations
Written by experienced plugin developers,
also helps you internationalize and localize your WordPress website. Find out about debugging systems and optimizing your site for speed. As WordPress use continues to increase, you can elevate your professional knowledge of how to extend WordPress through plugins.

Professional WordPress Plugin Development — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Professional WordPress Plugin Development», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

NOTE Menus are a common feature in WordPress plugins and are generally expected by users. It's a good idea to mention where your plugin settings can be found in the plugin description and documentation.

Adding a Submenu

Now that you have a new top‐level menu created, create some submenus for it, which are menu items listed below your top‐level menu. For example, Settings is a top‐level menu, whereas General, listed below Settings, is a submenu of the Settings menu. To register a submenu, use the add_submenu_page()function.

The add_submenu_page()function accepts the following parameters:

parent_slug: Slug name for the parent menu ( menu_slug previously defined)

page_title: Title of the page as shown in the

menu_title: Name of your submenu displayed on the Dashboard

capability: Minimum capability required to view the submenu

menu_slug: Slug name to refer to the submenu; should be a unique name

function: Function to be called to display the page content for the item

Now that you know how submenus are defined, you can add one to your custom top‐level menu.

The preceding code creates three submenus for your custom top‐level menu: About, Help, and Uninstall, as shown in Figure 3‐2. Each of these submenu items links to a different custom function that can contain any code you want to use for that submenu page.

FIGURE 32 Submenus NOTE Not all plugins will need submenus For example a - фото 7

FIGURE 3‐2 : Submenus

NOTE Not all plugins will need submenus. For example, a plugin with a single settings page has no need for additional submenus. When creating your new plugin, it's important to determine if submenus will be needed for a good user experience.

Adding a Menu Item to an Existing Menu

If your plugin requires only a single options page, you may not need to create a custom top‐level menu. Instead, you can simply add a submenu to an existing menu, such as the Settings menu.

WordPress features many different functions to add submenus to the existing default menus in WordPress. One of these functions is the add_options_page()function. Now explore how the add_options_page()function works to add a submenu item to the Settings menu.

The add_options_page()function accepts the following parameters:

page_title: Title of the page as shown in the

menu_title: Name of your submenu displayed on the Dashboard

capability: Minimum capability required to view the submenu

menu_slug: Slug name to refer to the submenu; should be a unique name

function: Function to be called to display the page content for the item

Now add a submenu item to the Settings menu.

The preceding code adds a submenu labeled PDEV Settings under the Settings menu, as shown in Figure 3‐3. Set the page title to PDEV Plugin Settings, set the capability to manage_optionsso that only administrators can view it, and set the function pdev_plugin_option_page()to be called when the submenu is clicked.

FIGURE 33 Submenu labeled PDEV Settings The following is a list of all - фото 8

FIGURE 3‐3 : Submenu labeled PDEV Settings

The following is a list of all available submenu functions in WordPress:

add_dashboard_page: Adds a submenu to the Dashboard menu

add_posts_page: Adds a submenu to the Posts menu

add_media_page: Adds a submenu to the Media menu

add_links_page: Adds a submenu to the Links menu

add_pages_page: Adds a submenu to the Pages menu

add_comments_page: Adds a submenu to the Comments menu

add_theme_page: Adds a submenu to the Appearance menu

add_plugins_page: Adds a submenu to the Plugins menu

add_users_page: Adds a submenu to the Users menu

add_management_page: Adds a submenu to the Tools menu

add_options_page: Adds a submenu to the Settings menu

To use any of these functions, simply swap out the function name in the code shown earlier.

NOTE If your plugin requires only a single options page, it's best practice to add it as a submenu to an existing menu. If you require more than one, create a custom top‐level menu.

PLUGIN SETTINGS

Now that you've learned how to create menus and submenus in the WordPress Dashboard, it's time to create a settings page for your plugin. WordPress enables easy access to the database to store and retrieve data, such as options end users can modify and save in settings pages or internal information plugins you need to know. You'll learn how to save and fetch this data using the Options API and internal WordPress functions.

THE OPTIONS API

The Options API is a set of functions that enable easy access to the database where WordPress, plugins, and themes save and fetch needed information.

Options are stored in a database table named, by default, wp_options and can be text, integers, arrays, or objects. For example, WordPress keeps in this table the title of your blog, the list of active plugins, the news articles displayed on the Dashboard, or the time to check if a new version is available.

You'll now learn how to use the functions to access, update, and save options: add_option(), update_option(), get_option(), and delete_option().

Saving Options

You start by saving your first plugin option, which will be named pdev_plugin_colorand have a value of red. The function call to do so is the following:

The add_option()function accepts the following parameters:

option: Name of the option to add

value: Value of the option you are adding

deprecated: Description, which is no longer used

autoload: Whether to load the option when WordPress starts

The first parameter is your option name. It is crucial that you make it unique and self‐explanatory.

Unique: It will never conflict with internal existing or future WordPress options or with settings that might be created by another plugin.

Self‐explanatory: Name it so that it's obvious it's a plugin setting and not something created by WordPress.

NOTE Using the same prefix, for example , pdev_plugin, for function names, options, and variables is highly recommended for code consistency and for preventing conflict with other plugins. The golden rule of “Prefix everything,” first introduced in Chapter 2, applies here.

The second parameter is the option value that can be practically anything a variable can hold: string, integer, float number, Boolean, object, or array.

Saving an Array of Options

Every option saved adds a new record in WordPress’ option table. You can simply store several options at once, in one array. This avoids cluttering the database and updates the values in a single MySQL query for greater efficiency and speed.

$options = array( 'color' => 'red', 'fontsize' => '120%', 'border' => '2px solid red' ); update_option( 'pdev_plugin_options', $options );

Saving your plugin options in one array rather than individual records can have a huge impact on WordPress’ loading time, especially if you save or update many options. Most of the time, PHP code executes fast, but SQL queries usually hinder performance, so save them whenever possible.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Professional WordPress Plugin Development»

Представляем Вашему вниманию похожие книги на «Professional WordPress Plugin Development» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Professional WordPress Plugin Development»

Обсуждение, отзывы о книге «Professional WordPress Plugin Development» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x