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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

Any file can be passed into the function. The resulting path will point to wherever the file lives in your plugin. If passing in __FILE__from the primary plugin file, it'll be the path to the root of your plugin. If passing it in from a subfolder in your plugin, it will return the path to the subfolder in your plugin.

Assuming you needed to load a file named /src/functions.phpfrom your plugin that houses some custom functions, use the following code:

It is common practice for plugin authors to store this path as a variable or constant in the plugin's primary file for quick access to the plugin's root folder path, as shown in the following example code:

This allows you to reference PDEV_DIRany time you need it from anywhere in the plugin without having to think about file paths.

URL Paths

Referencing URL paths can be tougher than local paths because there's usually no good way to determine this via standard PHP functions or constants alone. You'll need to rely on WordPress to get the correct path.

The primary use case for getting a URL path will be determining the path to an asset (e.g., JavaScript, CSS, or image files) within your plugin. WordPress provides the plugin_dir_url()function to handle this use case.

Parameters:

$file (string, required): The filename in the current directory path

WordPress will automatically convert any filename passed in to an appropriate URL equivalent. See the following example of passing in the filename from within the primary plugin file:

That code will output something like the following URL with a trailing slash:

https://example.com/wp-content/plugins/pdev/

If you wanted to determine the path of a JavaScript file located at /public/js/example.jsin your plugin, you'd use the following code:

You can use this to correctly get the URL path to any location in your plugin. Like its plugin_dir_path()counterpart, you can pass in any filename in your plugin to determine the appropriate URL for any location.

WordPress also provides a plugins_url()function. plugin_dir_url()is a wrapper for this function. For most purposes, these two functions can almost be used interchangeably, but there are some important differences.

Parameters:

$path (string, optional): A path to append to the end of the URL

$plugin (string, optional): The full path to a file within the plugin

If no parameters are provided, the function will return the URL to the plugin's directory for the WordPress installation. It also does not add a trailing slash to the end of the URL. For most cases, it's usually best to stick with plugin_dir_url(). However, this function is available if needed.

Other than determining the URL path to files within your plugin, you may need to determine the URL for a particular page or directory within the WordPress installation. WordPress has a number of useful functions that return the necessary information.

site_url(): URL path to where WordPress is installed

home_url(): URL path to the site's homepage

admin_url(): URL path to the WordPress admin

rest_url(): URL path the REST API endpoint

includes_url(): URL path to the WordPress includes directory

content_url(): URL path to the WordPress content directory

All of these URL functions accept an optional first parameter of $path, which is appended to the end of the URL if provided. The following example shows how to retrieve the URL path to the General Settings page in the admin:

With the exception of the content_url()function, each of these functions also accepts an optional second parameter of $scheme, which allows you to manually set the protocol, such as 'http'or 'https'. In almost all cases, you should not set this parameter and should instead allow WordPress to automatically determine the appropriate URL scheme.

First‐time WordPress developers will also sometimes confuse site_url()and home_url(). WordPress can be installed in a subdirectory on the server while allowing the actual site to be located elsewhere. Unfortunately, the function names are part of a legacy code base and have stuck around. The trick is to remember that the “home” in home_url()refers to the URL of the site, and the “site” in site_url()refers to the URL of the WordPress installation.

If WordPress is installed in a subdirectory, site_url()might point to a URL like https://example.com/wordpress, while home_url()points to https://example.com.

ACTIVATE/DEACTIVATE FUNCTIONS

WordPress provides standard activation and deactivation hooks that allow any plugin to run code when it is activated or deactivated, respectively. This section walks through how to use both.

Plugin Activation Function

When building plugins, you'll often need to execute some code when the user first activates it. One common use case is adding custom capabilities to the administrator role (see Chapter 9, “Users and User Data”) for something like a custom post type (see Chapter 8, “Content”) that your plugin is registering. Or, you may need to set up a particular option for your plugin to perform.

WordPress provides the register_activation_hook()function that allows you to pass in a callback for handling any activation code you need to run.

Parameters:

$file (string, required): Filesystem path to the primary plugin file

$function (callable, required): The PHP callable to be executed when the plugin is activated

It's generally best to separate your activation code from the rest of your plugin code simply for organizational purposes. The following example shows how to register an activation hook that points to a class located at src/Activation.phpin your plugin and executes its activate()method:

The add_menu_page()function accepts the following parameters:

page_title: Title of the page as shown in the

menu_title: Name of your menu displayed on the Dashboard.

capability: Minimum capability required to view the menu.

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

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

icon_url: URL to a custom image to use as the menu icon. Also supports the dashicons helper class to use a font icon (e.g. dashicons‐chart‐pie).

position: Location in the menu order where it should appear.

Now create a new menu for your plugin to see the menu process in action. Use the admin_menuaction hook to trigger your menu code. This is the appropriate hook to use whenever you create menus and submenus in your plugins.

As you can see, the admin_menuaction hook calls your custom pdev_create_menu()function. Next you need to call the add_menu_page()function to register the custom menu in WordPress. Set the name of your menu to PDEV Settings, require that the user has manage_optionscapabilities (that is, is an administrator), and set the callback function to pdev_settings_page(). You also set the menu icon to use the built‐in smiley dashicon (covered in detail later in this chapter). The final parameter is the menu position, which defines where the menu will appear within the WordPress Dashboard's left menu.

The result is a custom registered menu as shown in Figure 3‐1.

FIGURE 31 Custom registered menu NOTE Menus are a common feature in - фото 6

FIGURE 3‐1 : Custom registered menu

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

Интервал:

Закладка:

Сделать

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

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


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

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

x