HOWTO.wordpress_development - raynaldmo/HOWTO GitHub Wiki

Jobs

Resources

WordPress Development Course List

WordPress vs Drupal

Development Environment & Tools

Local By Flywheel

Database

  • Connect to database
mysql -h <remote host> -P <remote port> -u root -p
mysql -h 192.168.95.100 -P 4006 -u root -p

SSH

WP-CLI

Debugging

Debugging Plugins

WordPress Development

Resources

WordPress Theme Development

Resources

Theme Basics

  • Experiment with custom theme design using Underscores (underscores.me) Starter Theme
  • Create vanilla theme using https://underscores.me site
    • Fill out theme name etc.
    • Afterwards zip file is created
    • Download the file and install in wp-content/themes directory
  • There are two parts to every theme
    • Frontend - HTML, CSS, JavaScript
    • Backend - PHP template files
  • The following sections focus on the back-end of theme design
    • Template files
    • Template tags (functions)
    • Theme functions - functions.php
    • Template file directory structure

Template Files

  • WordPress themes are made up of template files - located at wp-content/themes/{theme_name}
  • Template files are PHP files that contain a mixture of HTML, Template tags, and PHP code
  • These files determine how a particular piece of content is displayed
  • style.css is the main css file
  • style.css also contains (required) theme information in a header (Theme name, version, author)
  • Example Template files: index.php, single.php, page.php, seach.php, comments.php, 404.php
  • index.php and style.css must always be present in a theme

Template Hierarchy

  • Template Hierarchy is the logic WordPress uses to decide which theme template file(s) to use
    depending on the content being requested
  • It's how WordPress decides which file to use for displaying
    • the front page
    • a single post
    • a taxonomy page
    • or any other page
  • WordPress uses the query string in the page URL to decide which template or set of templates should be used to display the page
  • Use What the File Plugin to show what template file is being used for a particular page

Template Tags

  • Template Tags
  • List of Template Tags
  • Template tags are PHP functions and used within themes to retrieve content from the site
    database
  • Template tags files are in the wp-includes directory and have suffix -template.php
  • Themes can also create an unlimited number of custom template tags/functions
    • e.g see wp-content/themes/vanilla/inc/template-tags.php
  • Example Template tags
    • get_header()
    • the_content()
    • the_ID()
    • the_meta()
    • get_sidebar()
    • get_footer()

Theme Functions

  • Every theme comes with a functions.php file
  • functions.php is where you add unique features to your theme - basically behaves like
    a Plugin
  • It can be used to hook into the core functions of WordPress to make a theme more
    modular, extensible, and functional
  • Use {theme_name}_widgets_init() to add Sidebars for adding widgets

Including CSS and JavaScript

  • In functions.php use wp_enqueue_script() and wp_enqueue_style()

Custom Headers

  • Reference https://developer.wordpress.org/themes/functionality/custom-headers/
  • Custom headers is an optional feature and allow site owners to upload their own
    “title” image to their site
  • This image can be placed at the top of certain pages
  • Go to Customizer -> Header Image (or from Dashboard, Appearance -> Header Image)
    • Note: some themes may not have this option or put this option in another place

Customizer Integration

  • Reference https://developer.wordpress.org/themes/customize-api/
  • The Customizer provides a unified interface for users to customize various aspects of
    their theme and their site
    • Colors
    • Layouts
    • Widgets
    • Menus, and more
  • Themes and plugins alike can add options to the Customizer
  • See wp-content/themes/motorcycles/inc/customizer.php

WordPress CSS and Menus

How to Add CSS Styles

  • Use Chrome developer tools Sources Tab and add styles to style.css

How to Create Menu Locations

  • HTML for Primary navigation menu is in header.php template file
  • Relevant functions
    • register_nav_menus() - Registers navigation menu locations (e.g. Primary etc.)
    • wp_nav_menu() - Displays a navigation menu
  • Create menus
    • Go to Dashboard -> Appearance -> Menus

How to Place Menus

Add navigation menu into footer area

  • Register menu
    • In functions.php:register_nav_menus() add footer entry
  • Create new menu and add menu links
    • From Dashboard: Appearance -> Menus -> Create new menu (Footer Menu)
    • Add menu links via Appearance -> Menu UI
  • Add <nav id="footer-navigation" class="footer-navigation"> to footer.php
    • Menu is added via wp_nav_menu() call

WordPress Theme Widgets

How to Register Widget Areas

  • A Widget is a small block that performs a specific function
    • Calendar widget
    • Search form widget
    • Custom HTML widget
    • Recent Posts widget
  • Underscores has a single, default Sidebar for adding widgets
  • Sidebar is a misnomer - a better name is Widget Area
  • Widget Areas can be placed anywhere on page - header, footer, embedded in posts etc.
  • In functions.php
    • Use register_sidebar() to add Header and Footer Widget Areas

How to Render Widget Areas

  • Use get_sidebar() function to add widget area

Add Widget Area in Header

  • In header.php add <?php get_sidebar('vanilla-header-widgets'); ?>
  • Add file sidebar-vanilla-header-widgets

Add Widget Area in Footer

  • In footer.php add <?php get_sidebar('vanilla-footer-widgets'); ?>
  • Add file sidebar-vanilla-footer-widgets

WordPress Theme Code Standards

How to Enqueue Scripts

  • In functions.php:vanilla_scripts() use
    • wp_enqueue_style() to load css files
    • wp_enqueue_script() to load JavaScript files
  • Add PT Sans Google font
    • Add wp_enqueue_style( 'motorcycles-font-pt-sans', '//fonts.googleapis.com/css?family=PT+Sans&display=swap' );

WordPress Loop

  • WordPress Loop
  • The Loop refers to the code (mostly PHP) used by WordPress to retrieve and display web page content
  • This includes pages containing:
    • post post type
    • page post type
    • custom post type / custom content
  • Basic index.php template file using the Loop
<?php
get_header();
?>
  <div id="main">
    <?php
    if ( have_posts() ) :
      while ( have_posts() ) :
        the_post();
    ?>
        <a href="<?php the_permalink();?>"><?php the_title('<h1>', '</h1>');?></a><br/>
        <?php the_excerpt();?>

    <?php
      endwhile;
    endif;
    ?>
  </div><!-- #main -->

<?php
get_footer();

WordPress Post Types

  • Post Types
  • Custom Post Types
  • GenerateWP - Code Generation
  • Post types refer to different Content types
  • Out of the box, WordPress supports the following Post types:
    • Post (Post Type: ‘post’)
    • Page (Post Type: ‘page’)
    • Attachment (Post Type: ‘attachment’)
    • Revision (Post Type: ‘revision’)
    • Navigation menu (Post Type: ‘nav_menu_item’)
  • Use register_post_type() to create custom post types

Custom Post Type Plugins

WordPress Taxonomies

  • Taxonomies
  • A Taxonomy is a fancy word for classifying/grouping of things
  • Taxonomies can be hierarchical (with parents/children) or flat

WordPress Custom Fields (Metadata) & Meta Boxes

Adding / Retrieving Metadata

  • Post metadata
    • add_post_meta(), get_post_meta()
  • User metadata
    • add_user_meta(), get_user_meta()
  • Comment metadata
    • add_comment_meta(), get_comment_meta()
  • Term metadata
    • add_term_meta(), get_term_meta()

Meta Boxes

  • Meta Boxes
  • Meta boxes are boxes (form fields) within a post editing screen that allow users to edit metadata
  • Use add_meta_box() to add a meta box to a post editing screen

Custom Field Plugins

Form Handling

WordPress Plugin Development

Resources

Plugin Overview

  • Plugins extend the core functionality of WordPress
  • Plugins consist of PHP code and can include other assets such as images, CSS, and JavaScript

Plugin Activation and Deactivation

Registration Hooks

  • register_activation_hook() - runs when plugin is activated
  • register_deactivation_hook() - runs when plugin is deactivated
  • register_uninstall_hook() - runs when plugin is uninstalled
  • Never echo/print anything for any of these above three hooks
  • register_activation_hook()
    • must be called from within the main plugin file
    • must not be registered from within another hook (e.g., "plugins_loaded" or "init") because such hooks are called before the plugin is activated
  • If the activation callback function is located in any file other than the main plugin file, include the file before registering with the activation hook
include_once dirname( __FILE__ ) . '/includes/activation.php';
register_activation_hook( __FILE__, 'myplugin_activation_function' );

Plugin Uninstall

  • When a plugin is uninstalled any database data added by the plugin should be removed
  • Two ways to accomplish this
    • Use register_uninstall_hook() or
    • Use uninstall.php file - Preferred technique

register_uninstall_hook()

  • Example code
// Remove options on uninstall
function sample_plugin_on_uninstall() {
  if ( ! current_user_can( 'activate_plugins' ) ) return;
  delete_option( 'sample_plugin_options' );
}
register_uninstall_hook( __FILE__, 'sampl_plugin_on_uninstall' );

uninstall.php file

  • Example file
<?php // uninstall.php - fires when plugin is uninstalled via the Plugins screen

// exit if uninstall constant is not defined
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
  exit;
}

// delete plugin options
delete_option( 'sample_plugin_options' );

Notes

Delete options:               delete_option()
Delete options (Multisite):   delete_site_option()
Delete transient:             delete_transient()
Delete metadata:              delete_metadata()

Delete database table:
global $wpdb;
$table_name = $wpdb->prefix . 'myplugin_table';
$wpdb->query( "DROP TABLE IF EXISTS {$table_name}" );

Delete cron event:

$timestamp = wp_next_scheduled( 'sfs_cron_cache' );
wp_unschedule_event( $timestamp, 'sfs_cron_cache' );

Action and Filter Hooks

Action Hook Functions

  • do_action() - Dispatch actions for given event (separate parameters)
  • do_action_ref_array() - Dispatch actions for given event (array parameter)
  • add_action() - Add action handler
  • remove_action() - Remove action handler
  • remove_all_actions() - Remove all action handlers
  • has_action() - Check if hook has an action handler
  • did_action() - Check if an action has been dispatched
  • current_action() - Determine action that is being dispatched

Common Action Hooks used by Plugins

  • plugins_loaded - fired after WordPress had loaded all plugins (only available to Plugins)
  • init - fired after most of WordPress is setup
  • admin_menu - fired early in page load process - used to register custom admin pages
  • save_post - fired after a post is saved - can be used to store meta-data when a post is saved
  • wp_head - fires when a theme calls wp_head() - allows a plugin to insert data in page <head>

Filter Hook Functions

  • apply_filter() - Dispatch filters (separate parameters)
  • apply_filters_ref_array() - Dispatch filters (array parameter)
  • add_filter() - Add filter handler
  • remove_filter() - Remove filter handler
  • remove_all_filters() - Remove all filter handlers
  • has_filter()
  • current_filter()

Common Filter Hooks used by Plugins

  • the_content - filters the output of post content
  • template_include - filters the path of the current template before including it

Custom Hooks

  • Custom hooks make your plugin more flexible by allowing it to be extended by other plugin
    and theme developers
  • Plugins can create hooks (similar to WordPress core) by using the following calls
  • do_action()
  • do_action_ref_array()
  • apply_filters()
  • apply_filters_ref_array()

Variable Hooks

  • Variable hooks are hooks that use PHP variables in their name - the hook's name changes
    based on the variable's current value
// Variable hook example
do_action("save_post_{$post->post_type}", $post-ID, $post, true);
// Hook name depends on post type and could be:
save_post_post
save_post_page
save_post_movie (for custom movie post type)
etc.

Pluggable Functions

  • Codex - Pluggable Functions
  • Pluggable Functions let you override certain core functions via plugins
  • These functions are located in 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 should use filters on their output to allow for similar overriding of their functionality

Security Techniques

Checking Users

Data Validation

  • Data validation is the process of analyzing the data against a predefined pattern (or patterns)
    with a definitive result - valid or invalid
  • Applies to data coming from external sources such as user input and Web API calls

Sanitizing Input

  • Sanitizing input is the process of cleaning/filtering input data
  • Data Sanitization Examples
    • Display data as HTML - Sanitize the data as HTML
    • Display data as an attribute - Sanitize the data as an attribute
    • Display data as a URL - Sanitize the data as a URL
    • Display data as "x" - Sanitize the data as "x"
  • Use sanitize_*() functions to sanitize input
    • sanitize_text_field()
    • sanitize_title()
    • sanitize_textarea_field()

Sanitizing Output

  • Securing Output
  • Sanitizing output is the process of Escaping output data
  • Escaping means stripping out unwanted data, like malformed HTML or script tags
  • Escaping output prevents XSS (Cross-site scripting) attacks
  • Whenever rendering data, make sure to properly escape it
    • esc_attr()
    • esc_html()
    • esc_js()
    • esc_textarea()
    • esc_url()
    • wp_kses_post()
    • and more

Nonces

  • Nonces
  • Using Nonces
  • Nonces are one-time use security tokens generated by WordPress to help protect URLs and forms from misuse

Querying and Displaying Posts / Content

  • Generally speaking, WordPress automatically queries content from the database on a given page view_

    • then the selected template file (based on template hierarchy) is selected to render the content
  • Plugins can also pull in content from the database using three main ways:

    • WP_Query class
    • get_posts() function
    • pre_get_posts() function
  • Content can then be displayed/rendered via

    • Shortcode
    • Widgets
    • Blocks

Shortcodes

  • Shortcodes
  • Shortcode API
  • Shortcodes are basically macros and are one way plugins can add dynamic content to posts and pages
  • Note: Shortcodes are becoming obsolete
    While they always will be in WordPress (for backward compatibility), blocks or widgets should be used instead
  • Built-in WordPress Shortcodes
    • [caption] – shortcode that allows you to wrap captions around content
    • [gallery] – shortcode that allows you to show image galleries
    • [audio] – shortcode that allows you to embed and play audio files
    • [video] – shortcode that allows you to embed and play video files
    • [playlist] – shortcode that allows you to display collection of audio or video files
    • [embed] – shortcode that allows you to wrap embedded items

Widgets

Blocks

Getting Data

  • WordPress core provides many functions to get any needed data
    • get_post()
    • get_userdata()
    • get_category()
    • get_comment()
    • get_attached_media()
    • get_metadata()
    • etc
  • There may be times though when you can't find a core function to get the data that you need
  • For these cases, WordPress provides the global $wpdb object (and its methods) to directly interact with the database
  • See Talking to the Database: The wpdb Class

Custom Post Types

Managing Users and Roles

Working with JavaScript and CSS

  • Use the following functions to add JavaScript and CSS from plugins

    • wp_enqueue_script() - Add JavaScript file(s)
    • wp_add_inline_script() - Add inline JavaScript
    • wp_enqueue_style() - Add CSS file(s)
    • wp_add_inline_style() - Add inline CSS
  • Action Hooks

    • wp_enqueue_scripts - Enqueue JavaScript and CSS on public facing pages
    • admin_enqueue_scripts - Enqueue JavaScript and CSS on admin pages
    • login_enqueue_scripts - - Enqueue JavaScript and CSS on login page
  • Also can use

    • wp_register_script()
    • wp_register_style()

Options API

  • Options API
  • Options API offers a simple and standardized way of storing data in the database
    • Makes it easy to create, access, update, and delete options
    • Data can be integers, arrays or objects
  • Options API can be used independently from the Settings API
  • All options are stored by default in the wp_options table
  • WordPress core, Plugins, and Themes store configuration, settings and data in the wp_options table

Transients API

  • Transients API
  • Transients offers a simple and standardized way of storing cached / temporary data in the WP database
    • Idea is to improve performance
  • Similar to the Options API but with the added feature of an expiration time
  • Data is normally stored in wp_options database table but can be stored in memory with plugins

HTTP API

REST API

WP-Cron

Plugin Internationalization

  • Internationalization
  • Translating WordPress
  • Internationalization is the process of developing a plugin so it can easily be translated into other languages
  • Internationalization (i18n)
    • Process of developing plugin so that it can be translated to other languages
  • Localization (l10n)
    • Process of translating an internationalization plugin

Plugin Development Outline

  • Plugin Boilerplate
  • Code Generation
  • Plan Plugin Directory Structure
  • Create Administration Menu
  • Create Settings Page
    • Decide on fields to use - text field, radio input, text-area, select list
  • Implement plugin's core functionality
⚠️ **GitHub.com Fallback** ⚠️