Presentation is loading. Please wait.

Presentation is loading. Please wait.

WordPress Plugin Development

Similar presentations


Presentation on theme: "WordPress Plugin Development"— Presentation transcript:

1 WordPress Plugin Development
Sharee English

2 Agenda Overview of PHP Plugin Framework Basics
User Settings and Administration Pages Custom Post Types Customizing Post and Page Editors Accepting User Content Submissions Customizing User Data Creating Custom MySQL Database Tables

3 PHP Basics W3Schools

4 PHP vs JavaScript Similarities Differences Back-End Development Syntax
Entry points Object-Oriented Programming (OOP) Compiled vs. Interpreted Memory safe Static vs. Dynamic Type Checking Concurrency Class-Based vs. Prototype Based

5 Getting Started with Plugin Development
Creating a plugin file and header Adding output content to page headers using plugin actions Using WordPress path utility functions to load external files and images Modifying the site generator meta tag using plugin filters Adding text after each item's content using plugin filters Inserting link statistics tracking code in page body using plugin filters Troubleshooting coding errors and printing variable content Creating a new simple shortcode Creating a new shortcode with parameters Creating a new enclosing shortcode Loading a style sheet to format plugin output Writing plugins using object-oriented PHP

6 What are Plugins? Plugin – Provides a set of hooks that enable plugins access to specific parts of WordPress Action Hooks – Triggers custom plugin code as specific points during execution. For example you can trigger a custom function to run after a user registers a user account Filter Hooks – Modifies text before adding or after retrieving from the database Widgets – another word for Plugins. Provide a GUI option. Shortcode – anther word for Plugins. Provides the ability to add to the content using [shortcode]

7 Resources

8 How Plugins Interact wp_config Loaded Functions Loaded Plugins Loaded
Pluggables Loaded Translations Loaded Theme Loaded Page Content Pluggable functions were introduced in WordPress 1.5.1 These functions let you override certain core functions via plugins. The most up-to-date list of core functions that WordPress allows plugins to override is available at wp-includes/pluggable.php. WordPress loads the built-in functions only if they are undefined after all plugins have been loaded. Pluggable functions are no longer being added to WordPress core. All new functions instead use filters on their output to allow for similar overriding of their functionality. Note: A function can only be reassigned this way once, so you can’t install two plugins that plug the same function for different reasons. For safety, it is best to always wrap your functions with if ( !function_exists() ), otherwise you will produce fatal errors on plugin activation

9 Types of Plugins Active – plugins that are active and currently running Inactive – plugins that are installed but not active. No code from the plugin is executed. Must-Use – Installed in the wp-content/mu-plugins directory. These are loaded automatically and can only be deactivated by removing the plugin from the directory. Drop-ins – Core functionality of WordPress can be replaced by Drop-in plugins. These are specifically named PHP files Install.php – custom installation script Maintenance.php – custom maintenance message Db.php – Custom database class

10 File Organization Folder Structure
/Unique-Plugin-Name (no spaces or special characters) unique=-plugin-name.php (Primary plugin PHP file) Uninstall.php (the uninstall file for your plugin) /js (folder for JavaScript files) /css (folder for CSS files) /includes (folder for other PHP includes) /images (folder for plugin images)

11 Plugin Header Plugin Name: (required) The name of your plugin, which will be displayed in the Plugins list in the WordPress Admin. Plugin URI: The home page of the plugin, which should be a unique URL, preferably on your own website. This must be unique to your plugin. You cannot use a WordPress.org URL here. Description: A short description of the plugin, as displayed in the Plugins section in the WordPress Admin. Keep this description to fewer than 140 characters. Version: The current version number of the plugin, such as 1.0 or Author: The name of the plugin author. Multiple authors may be listed using commas. Author URI: The author’s website or profile on another website, such as WordPress.org. License: The short name (slug) of the plugin’s license (e.g. GPL2). More information about licensing can be found in the WordPress.org guidelines. License URI: A link to the full text of the license (e.g.  Text Domain: The gettext text domain of the plugin. More information can be found in the Text Domain section of the How to Internationalize your Plugin page. Domain Path: The domain path let WordPress know where to find the translations. More information can be found in the Domain Path section of the How to Internationalize your Plugin page.

12 Hooks Hooks are provided by WordPress to allow your plugin to 'hook into' the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks: Action – (2,400) enable execution of additional code at specific points of pages when they are displayed. This code usually adds content to a site or changes the way a given action is performed. Filter – Augment, modify or change information BEFORE it is displayed on the screen.

13 Action Hooks Actions are called with the following functions
do_action(string $tag, $arg = '' ) add_action( string $tag, callable $function_to_add, int $priority = 10,int $accepted_args = 1 )

14 Activation and Deactivation
Activation and deactivation hooks provide ways to perform actions when plugins are activated or deactivated. On activation, plugins can run a routine to add rewrite rules, add custom database tables, or set default option values. On deactivation, plugins can run a routine to remove temporary data such as cache and temp files and directories. function pluginprefix_setup_post_type() {     // register the "book" custom post type     register_post_type( 'book', ['public' => 'true'] ); } add_action( 'init', 'pluginprefix_setup_post_type' ); function pluginprefix_install() {     // trigger our function that registers the custom post type     pluginprefix_setup_post_type();     // clear the permalinks after the post type has been registered     flush_rewrite_rules(); register_activation_hook( __FILE__, 'pluginprefix_install' ); function pluginprefix_deactivation() {     // unregister the post type, so the rules are no longer in memory     unregister_post_type( 'book' );     // clear the permalinks to remove our post type's rules from the database register_deactivation_hook( __FILE__, 'pluginprefix_deactivation' );

15 Filter Hooks Augment, modify or change information BEFORE it is displayed on the screen. add_filter( string $tag,  callable $function_to_add, int $priority = 10,int $accepted_args = 1 )

16 Misc functions

17 Debugging No debugger (Doh!)
Enable built-in debugger (not much better) Download Debugger (something is better than nothing)

18 Shortcodes There can only be one hook for each shortcode. Which means that if another plugin has a similar shortcode, it will override yours or yours will override theirs depending on which order the plugins are included and/or ran. Shortcode attribute names are always converted to lowercase before they are passed into the handler function. Values are untouched. Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results. This is similar to the way filter functions should behave, in that they should not produce expected side effects from the call, since you cannot control when and where they are called from.

19 Shortcodes with Parameters
Shortcode handler function can accept 3 parameters: $atts – array – [$tag] attributes $content – string – post content $tag – string – the name of the [$tag] (i.e. the name of the shortcode)

20 Adding Styles to format Plugins
Enqueuing Scripts and Styles The proper way to add scripts and styles to your theme is to enqueue them in the functions.phpfiles. The style.css file is required in all themes, but it may be necessary to add other files to extend the functionality of your theme. Rather then loading the stylesheet in your header.php file, you should load it in using wp_enqueue_style. In order to load you main stylesheet, you can enqueue it in functions.php

21 User Settings and Administration Pages
Creating default user settings on plugin initialization Storing user settings using arrays Removing plugin data on deletion Creating an administration page menu item in the settings menu Creating a multi-level administration menu Adding menu items leading to external pages Hiding items that users should not access from the default menu Rendering the admin page content using HTML Processing and storing plugin configuration data Displaying a confirmation message when options are saved Adding custom help pages Rendering the admin page contents using the Settings API Accessing user settings from action and filter hooks Formatting admin pages using meta boxes Splitting admin code from the main plugin file to optimize site performance Storing style sheet data in user settings Managing multiple sets of user settings from a single admin page Creating a network level plugin with admin pages

22 Default User Settings Can be set individually
Must have unique names for each element Requires multiple database calls for setup and cleanup Can be set through an array Names can be anything (as they are elements of an array) Can retrieve information with one function call Makes bulk cleanup easier

23 Does uninstall.php exist?
Deleting Plugins Delete Plugin Does uninstall.php exist? Delete all Files No Yes Run uninstall.php code

24 Creating Administration Pages
Administration pages can be a single page for configuration or a menu of separate pages Single Page – adds a sub menu page to the settings menu add_options_page ($page_title, $menu_title, $capability, $menu_slug, $function) Multiple Pages – creates a main menu page with sub menus add_menu_page( string $page_title, string $menu_title,  string $capability,string $menu_slug,  callable $function = '', string $icon_url = ‘’, int $position = null ) add_submenu_page($page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position) Add_options_page – adds a sub menu page to the Settings menu

25 Display Saved Options WordPress does not provide any user feedback after configuration data has been saved. When a redirect call is made, user submitted fields and PHP variables do not carry forward. Use query arguments to determine a confirmation message should be displayed. // Redirect the page to the configuration form that was // processed wp_redirect(add_query_arg(array('page'=>'ch2pho-my-google-analytics','message'=>'1' ),admin_url('options-general.php'))); exit;

26 Using the Settings API Standardized way of storing data in the database Avoids complex debugging (as in previous examples) Forms post to the wp-admin/options.php Also using the OPTIONS API – which is an easy way to create, access, update and delete options Settings API Options API

27 Separating Admin Code When the MAIN CODE file of a WordPress plugin runs – THE ENTIRE CONTENT of the file gets evaluated. Large amounts of PHP code can potentially be parsed on every iteration Wasting processing power on the site's server Some of this code will never be active when regular visitors are browsing the site.

28 Custom Post Types Creating a custom post type
Adding a new section to the custom post type editor Displaying single custom post type items using custom layout Displaying custom post type data in shortcodes Adding custom categories for custom post types Adding custom fields to categories Hiding the category editor from the custom post type editor Displaying additional columns in the custom post list page Adding filters for custom categories to the custom post list page Adding Quick Edit fields for custom categories Updating a page title to include custom post data using plugin filters

29 What is Custom Post Type in WordPress?
Custom post types are content. The primary content types are Post and Page. WordPress comes with these post types: Post Page Attachment Revision Nav Menu Post types you may want to create: Products (for shopping) Reviews (for movies, books, food) Testimonials Portfolios Recipes

30 Custom Fields WordPress has the ability to allow post authors to assign custom fields to a post. This arbitrary extra information is known as meta-data. This meta-data can include bits of information such as: Mood: Happy Currently Reading: Cinderella Listening To: Rock Around the Clock Weather: Hot and humid With some extra coding, it is possible to achieve more complex actions, such as using the metadata to store an expiration date for a post. Meta-data is handled with key/value pairs. The key is the name of the meta-data element. The value is the information that will appear in the meta-data list on each individual post that the information is associated with.

31 Things to know The function update_post_meta() updates the value of an existing meta key (custom field) for the specified post. This may be used in place of add_post_meta() function. The first thing this function will do is make sure that $meta_key already exists on $post_id. If it does not, add_post_meta($post_id, $meta_key, $meta_value) is called instead and its result is returned. Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure. It also returns false if the value submitted is the same as the value that is already in the database.

32 Creating a custom post type
Requires 1 function function create_movie_post_type() Must be called from an action hook callback add_action(‘init’, ‘create_movie_post_type’) Check out

33 Creating Shortcodes – Shortcode API
A simple set of functions for creating WordPress shortcodes for use in posts and pages. Shortcodes are created by defining a function for the code and calling the add_shortcode Action hook Shortcodes are added to pages by inserting square brackets and the name of the shortcode Example: [tab] or [gallery]

34 WP_Query Deals with the internals of a request
Scenario #1 – What type of request is being asked Scenario #2 – Look to get all the values of the request

35 Taxonomy Classification or grouping Taxonomy Generator Review Book
Movie

36 WordPress REST API Separates the content of a site from its presentation without having to go through a theme, RSS feed, or XML To take full advantage must have deep knowledge of JavaScript You will be able to Create Read Update Delete

37 WordPress Data Limitation such as having to write custom PHP to output to a mobile app Bypasses the previous process and allows submitting a standard HTTP request or URL Can then use Ruby, or C# or JavaScript or whatever you want Can bypass WordPress Admin

38 Terms REST API JSON

39

40

41 Example

42 What is Authentication?
English, Sharee

43 English, Sharee

44

45 smith senglish senglish phillipson morrison hamilton

46 smith senglish senglish phillipson morrison hamilton senglish

47

48 REST API - CRUD

49

50

51 Outside of Context: Stand-Alone App

52 mySQL Database The mysql functions - (DEPRECATED)
MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. PDO (PHP Data Objects) is a general database abstraction layer with support for mySQL among many other databases.


Download ppt "WordPress Plugin Development"

Similar presentations


Ads by Google