Cheat Sheets Wordpress


WordPress Developer Super Cheat Sheet


There sure is a lot you need to remember when working with WordPress theme files.

From the names of basic template files to functions and how the WordPress Loop works, it’s next to impossible to remember every PHP tag or even how to define a new theme.

Theme Files

These are the basic files that every theme should include:

Defining a New Theme

Your stylesheet doesn’t just contain styling information for your theme – it also holds details about your theme that are displayed in the Appearance > Themes section of your WordPress admin.

The following is an example of the first few lines of the stylesheet for the default Twenty Sixteen theme:

/*
Theme Name: Twenty Sixteen
Theme URI: https://wordpress.org/themes/twentysixteen/
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Twenty Sixteen is a modernized take on an ever-popular WordPress layout — the horizontal masthead with an optional right sidebar that works perfectly for blogs and websites. It has custom color options with beautiful default color schemes, a harmonious fluid grid using a mobile-first approach, and impeccable polish in every detail. Twenty Sixteen will make your WordPress look beautiful everywhere.
Version: 1.2
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: black, blue, gray, red, white, yellow, dark, light, one-column, two-columns, right-sidebar, fixed-layout, responsive-layout, accessibility-ready, custom-background, custom-colors, custom-header, custom-menu, editor-style, featured-images, flexible-header, microformats, post-formats, rtl-language-support, sticky-post, threaded-comments, translation-ready
Text Domain: twentysixteen
This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
*/

This information goes at the top of your stylesheet.css file.

Template Include Tags

Template include tags are used within one template file (for example index.php) to include (or call) the HTML and PHP found in another template file (for example header.php). While PHP has its own built-in include() statement to do this, these WordPress-specific tags make life much easier:

Template Header/Bloginfo Tags

These are functions you’ll find in your theme’s header.php file, though you’ll also find them in other theme files:

Template Tags

These tags can be used across all of your template files, such as index.php or page.php, making it easy to display specific information anywhere you want on your site:

<?php the_content(); ?> – Displays the content of a post
<?php the_excerpt(); ?> – Displays the excerpt used in posts
<?php the_title(); ?> – Title of the specific post
<?php the_permalink() ?> – Link of a specific post
<?php the_category(', ') ?> – Category of a specific post
<?php the_author(); ?> – Author of a specific post
<?php the_ID(); ?> – ID of a specific post
<?php edit_post_link(); ?> – Edit link for a post
<?php next_post_link(' %link ') ?> – URL of the next page
<?php previous_post_link('%link') ?> – URL of the previous page
<?php get_links_list(); ?> – Lists all links in blogroll
<?php wp_list_pages(); ?> – Lists all pages
<?php wp_get_archives() ?> – List archive for the site
<?php wp_list_cats(); ?> – Lists all categories
<?php get_calendar(); ?> – Displays the built-in calendar
<?php wp_register(); ?> – Displays register link
<?php wp_loginout(); ?> – Displays login/logout link only to registered users


The Loop

The Loop is the default mechanism in WordPress for displaying all of your posts. Exactly how many posts are retrieved is determined by the number of posts you’ve chosen to display in the “Reading” settings in your WordPress dashboard.

Within the Loop, WordPress loops through each post retrieved for the current page one at a time and formats it according to your theme’s instructions.

You can use the Loop to do a lot of useful stuff, like:

<?php
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
//
// Post Content here
//
endwhile; // end while
endif; // end if
?>
view rawwordpress-loop hosted with ❤ by GitHub

The Loop can display lots of different element for each post. Some of the most common template tags used in themes (according to the WordPress Theme Handbook) are:

You can also use conditional tags, such as:

Wordpress Cheat sheet

Theme Headers style.css

/**
 * Theme Name:  My theme (required)
 * Template:    The name of the parent theme. E.g. Twenty Seventeen
 * Description: A short description of the theme.
 *
 * Theme URI:   Subject URL. E.g. http://wordpress.org/themes/twenty
 * Author:      Kama
 * Author URI:  https://wp-kama.com
 *
 * Tags:        black, brown, orange
 * Text Domain: Subject translation domain. E.g. twentythirteen
 *
 * License:     License. E.g. GNU General Public License v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Version:     1.0
 */

.htaccess code

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Theme Files (include)

Theme files include functions

Theme Files (hierarchy) /themes/THEME/

Theme Files Hierarchy
  • style.cssTheme styles file (required)
  • index.phpAny page without a template file (required)
  • front-page.phpFront (Home) page
  • home.phpPosts page (or Home page)
  • functions.phpA special file for php functions (code)
  • 404.phpPage "not found"
  • comments.phpComments Template (part)
  • header.phpSite Header Template (part)
  • searchform.phpSearch Form Template (part)
  • sidebar.phpSidebar Template (part)
  • footer.phpSite Footer Template (part)
  • single.phpPost page post_type = post
  • single-POST_TYPE.phpPost page post_type = POST_TYPE
  • single-POST_TYPE-POST_NAME.phpPost page with POST_NAME and POST_TYPE
  • singular.phpPost of any post type
  • page.phpPage post_type = page
  • page-POST_NAME.phpPage post_name = POST_NAME
  • page-ID.phpPage ID = ID
  • attachment.phpAny attachment page
  • image.phpImage attachment page
  • archive.phpPage of any archive
  • archive-POST_TYPE.phpPage of post type archive
  • search.phpSearch page
  • category.phpAny Category page
  • category-SLUG.phpCategory page with slug = SLUG
  • category-ID.phpCategory page with term_id = id
  • tag.phpAny Tag page
  • tag-SLUG.phpTag page with slug = SLUG
  • tag-ID.phpTag page with term_id = id
  • taxonomy.phpAny custom taxonomy element page
  • taxonomy-TAXONOMY.phpPage of any term of TAXONOMY taxonomy
  • taxonomy-TAXONOMY-SLUG.phpPage of SLUG term of TAXONOMY taxonomy
  • author.phpPage of Author posts

A post template from any file:

<?php
/*
Template Name: My page template
Template Post Type: post, page, product
*/

// … template file code

Site Information bloginfo

  • bloginfo()Displays information about the site.
  • get_bloginfo()Gets information about the site.
  •  
  • <?php bloginfo('name'); ?>Site name.
  • <?php bloginfo('description'); ?>Short description of the site.
  • <?php bloginfo('template_url'); ?>Theme URL: get_template_directory().
  • <?php bloginfo('template_directory'); ?>Same as template_url.
  • <?php bloginfo('stylesheet_directory'); ?>Theme URL: get_stylesheet_directory_uri().
  • <?php bloginfo('stylesheet_url'); ?>Theme file style.css URL: get_stylesheet_uri().
  • <?php bloginfo('charset'); ?>The site's encoding: UTF-8.
  • <?php bloginfo('html_type'); ?>Content-Type of the page: text/html.
  • <?php bloginfo('language'); ?>Site locale (language): RU.
  • <?php bloginfo('version'); ?>WordPress version: 5.5.3.
  • <?php bloginfo('rss2_url '); ?>URL of the feed: /feed.
  • <?php bloginfo('comments_rss2_url'); ?>URL of the comments feed: /comments/feed.
  • <?php bloginfo('admin_email'); ?>E-mail of Admin.
  •  
  • <?php bloginfo('pingback_url'); ?>Notification URL to the xmlrpc.php file.
  • <?php bloginfo('rdf_url'); ?>RDF/RSS 1.0 feed URL (/feed/rfd).
  • <?php bloginfo('rss_url'); ?>RSS 0.92 feed URL (/feed/rss).
  • <?php bloginfo('atom_url '); ?>Atom feed URL (/feed/atom).
  • <?php bloginfo('url'); ?>Home page URL. Alias home_url().
  • <?php bloginfo('wpurl'); ?>Admin panel URL. Alias site_url().

Comment Loop

The Loop

The Loop3 ways to Create Loop in WordPress
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
   <!-- Post output, loop functions: the_title(), etc. -->
<?php endwhile; else: ?>
	No posts.
<?php endif; ?>
<?php if ( have_posts() ){ while ( have_posts() ){ the_post(); ?>
	<!-- Post output, loop functions: the_title(), etc. -->
<?php } } else { ?>
	No posts.
<?php } ?>
<?php while ( have_posts() ){ the_post(); ?>
	<!-- Post output, loop functions: the_title(), etc. -->
<?php } ?>
<?php if ( ! have_posts() ){ ?>
	No posts.
<?php } ?>
<?php
global $post;

$myposts = get_posts([
	'numberposts' => 5,
	'offset'      => 1,
	'category'    => 1
]);

if( $myposts ){
	foreach( $myposts as $post ){
		setup_postdata( $post );
		?>
		<!-- Post output, loop functions: the_title(), etc. -->
		<?php
	}
} else {
	// No posts found
}

wp_reset_postdata(); // Reset $post
?>
<?php
global $post;

$query = new WP_Query( [
	'posts_per_page' => 5,
	'orderby'        => 'comment_count',
] );

if ( $query->have_posts() ) {
	while ( $query->have_posts() ) {
		$query->the_post();
		?>
		<!-- Post output, loop functions: the_title(), etc. -->
		<?php
	}
} else {
	// No posts found
}

wp_reset_postdata(); // Reset $post
?>

WP CLI

Core:

# Download WordPress
wp core download --locale=ru_RU

# Generate wp-config.php:
wp core config --dbname=NAME --dbuser=USER --dbpass=PASS --dbprefix=wp_

# Create DB (based on wp-config.php)
wp db create

# Install WP to created DB
wp core install --url=example.com --title=Example --admin_user=supervisor \
--admin_email=info@example.com --admin_password=strongpassword

Post:

# List posts:
wp post list

# Edit post:
wp post edit 1

# Post update:
wp post update 1 --post_title="Your New title..."

# Create posts:
wp post create --post_status=publish --post_title="Second Post" --edit

Post meta:

# See all metas of post 18:
wp post meta list 18

# Get post meta value:
wp post meta get 18 meta_name

# Delete post meta by key:
wp post meta delete 18 meta_name

DB:

# Create DB dump
wp db export - --add-drop-table --default-character-set=utf8mb4 | gzip > ./db-dump-$(date +%Y-%m-%d-%H%M%S).sql.gz

# Insert data from DB dump to DB
wp db import db_backup-2022-01-20.sql

# Login WordPress db:
wp db cli

# Run SQL Query:
wp db query "SELECT user_login, ID FROM wp_users;"

# Optimize db:
wp db optimize

Update:

# Update WordPress
wp core update

# Update all plugins:
wp plugin update --all

Themes & Plugins

# List plugins:
wp plugin list

# Search plugin:
wp plugin search yoast

# Install plugin:
wp plugin install yoast

# List installed themes:
wp theme list

# Install theme:
wp theme install twentyone

# Activate theme:
wp theme activate twentyone

Plugin Headers

<?php

/**
 * Plugin Name: My Plugin
 * Description: Description of the plugin (140 characters)
 *
 * Plugin URI:  URL to info about plugin
 * Author URI:  https://wp-kama.com
 * Author:      Kama
 *
 * Text Domain: Translation ID. E.g. my-plugin
 * Domain Path: Path to MO file (relative to plugin folder)
 *
 * Requires PHP: 7.0
 * Requires at least: 5.7
 *
 * License:     GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * Network:     true - activates the plugin for the whole network
 * Update URI:  https://example.com/link_to_update
 *
 * Requires Plugins: some-plugin, some-plugin-2
 *
 * Version:     1.0
 */

// plugin code

Plugin

Plugin Creation

uninstall.php

<?php
if( ! defined('WP_UNINSTALL_PLUGIN') ) exit;

// the check passed successfully. Starting from here remove all plugin data (options, db tables etc.).
delete_option( 'plug_option' );

Script and Style

Script & Style functions
add_action( 'wp_enqueue_scripts', 'add_my_scripts' );    // Front
add_action( 'admin_enqueue_scripts', 'add_my_scripts' ); // Admin
add_action( 'login_enqueue_scripts', 'add_my_scripts' ); // wp-login.php
function add_my_scripts(){

	if ( ! wp_script_is( 'my-script', 'enqueued' ) ) {
		// The my-script is not added to the queue
	}

	if ( ! wp_style_is( 'my-style', 'registered' ) ) {
		// Styles my-script is not registered
	}

	wp_enqueue_script( 'my-script', 'src', ['deps'], '1.0', 'in_footer' );
	wp_enqueue_style(  'my-style',  'src', ['deps'], '1.0', 'all' );

	wp_enqueue_style( 'theme-style', get_stylesheet_uri() ); // theme style.css

	wp_localize_script( 'my-script', 'myajax', [
		'ajaxurl' => admin_url( 'admin-ajax.php' )
	] );

	wp_script_add_data( 'my-script', 'conditional', 'lt IE 9' );
	wp_style_add_data(  'my-style',  'conditional', 'lt IE 9' )

	wp_add_inline_script( 'my-scripts', 'alert("Hello!");' );
	wp_add_inline_style( 'my-style', '
		.mycolor{
			background: #fff;
		}
	');

	wp_deregister_script( 'my-script' );
	wp_deregister_style( 'my-style' );
}

Hooks Functions

How hooks work in WordPressHooks execution order
function my_filter_function( $str ){
	return 'Hello '. $str;
}

// Let's attach a function to the filter
add_filter( 'my_filter', 'my_filter_function' );

// Call the filter
echo apply_filters( 'my_filter', 'John' ); //> Hello John
// Create a function for the event
function my_action_function( $text ){
	echo 'The my_action event has been triggered just now.';
}

// Let's attach the function to the my_action event
add_action( 'my_action', 'my_action_function' );

// Action call
do_action( 'my_action' ); //> The my_action event has been triggered just now.

Localization (translation)

Localization FunctionsTranslations in WordPress

Conditional tags (post types and queries)

if( is_single() ){
	// single post type page
}

Conditional tags (others)

if( is_user_logged_in() ){
	// user is authorized
}

Template Tags

All Template Tags

Formatting

Formatting

Escaping on output

Escaping on output

Sanitize on input

Sanitize on input