This function lets you display translated text on your page. First argument is the text to translate, second is the theme text domain.

#wordpress#php
_e('Hello', 'theme-name');
copy

Append css class to body using filter.

#wordpress#php
function add_your_body_class($classes) {
    $classes[] = 'new-class';
    return $classes;
}
add_filter('body_class', 'add_your_body_class');
copy

Add this method to the function.php file. It will append a stylesheet file in the admin area of WordPress so you can add your custom CSS in the editor. Don't forget to update path to the file.

#wordpress#php
function add_editor_stylesheet() {
   add_editor_style( 'path/to/css/file.css' );
}
add_action( 'admin_init', 'add_editor_stylesheet' );
copy

Modify and add it to the function.php file. It allows to add tags to the head section of the site.

#wordpress#php
function theme_add_head_tag() {
     ?>
     <link rel="preload" href="assets/background.jpg" as="image">
     <?php
    }
 }

 add_action( 'wp_head', 'theme_add_head_tag' );
copy

Register in the functions.php to add a new autogenerated image size for you posts and pages. Use name, width and height attributes to define the new size. By passing 9999 as a value of width or height the image will retain its original size for that dimension.

#wordpress#php
add_image_size( 'super-extra-large', 2400, 2000 );
copy

Adds post meta data fields to returned JSON data in the REST API. You can use it for default post types or custom ones.

#wordpress#php#rest#api
/**
* Register post meta data in REST
* Use rest_api_init to register post's meta data
*/
add_action( 'rest_api_init', 'add_post_meta_to_rest' );

function add_post_meta_to_rest() {

    $post_type = 'post'; // You can use taxonomy or a custom post name.
    $rest_name = 'post-meta' // All meta fields will be stored under this REST attribute.

    register_rest_field( $post_type, $rest_name, array(
        'get_callback' => function ( $object ) { return get_post_meta( $object['id'] ); },
        'schema' => null,
        )
    );
}
copy

Use add_shortcode function to register shortcode for later use. The first parameter is a name of your shortcode, the second is a callback function where you can add the content to return.

#wordpress#php
function wpshort_assemble_shortcode() { 
  
    $message = 'Hello from the shortcode!';       
    return $message;

}

/*
* Register shortcode
*/
add_shortcode('my_shortcode', 'wpshort_assemble_shortcode');

/*
* Use [my_shortcode] handle in a WYSIWYG editor to display it.
* Alternatively, you can use do_shortcode() function directly in code.
*/
copy

Use this filter to add a slug-based css class to each menu item.

#wordpress#php#menu
function add_menu_item_slug_class($classes, $item, $args) {

	$item_class = sanitize_title($item->title); // Convert title to a slug
	$classes[] = "menu-item-" . $item_class;

	return $classes;

}
add_filter('nav_menu_css_class', 'add_menu_item_slug_class', 1, 3);
copy

bloginfo function prints information about your site. Pass an argument to return name, description, wpurl, url, admin_email, charset, version, html_type, text_direction, language, stylesheet_url, stylesheet_directory, template_url, pingback_url and more.

#wordpress#php
bloginfo('url');
copy

This snippet checks if the logged in user has admin permissions and executes code if true.

#wordpress#php
if( current_user_can( 'administrator' ) ){
   // do something
}
copy

Check if post type matches the slug.

#wordpress#php
if( get_post_type() == 'recipes' ){
   echo 'This is a recipe post!';
}
copy

When registering a new custom post type you can encounter a bug where a single custom post returns a 404 page even when a valid page template exists. To fix it add the following snippet to the functions.php file. Make sure to remove it once the bug is fixed as you do not want it to run with each page load.

#wordpress#php
flush_rewrite_rules( false );
copy

Pass arguments to WP_Query with a tag of a custom post.

#wordpress#php
<?php // args
        $args = array(
        'post_type' => 'custom-post',
        'order' => 'ASC',
        'posts_per_page' => -1 // Get all posts
        );

        $the_query = new WP_Query( $args );
?>

<?php if( $the_query->have_posts() ): ?>
        <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
                <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
        <?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); // Reset loop ?>
copy

Disables Gutenberg editor and brings back the Classic editor. Additional actions remove related styles too.

#wordpress#php
/**
 * Disable Gutenberg on the back end.
 */
add_filter( 'use_block_editor_for_post', '__return_false' );

/**
 * Disable Gutenberg for widgets.
 */
add_filter( 'use_widgets_blog_editor', '__return_false' );

/**
 * Disable Gutenberg styles.
 */
add_action( 'wp_enqueue_scripts', function() {
    // Remove CSS on the front end.
    wp_dequeue_style( 'wp-block-library' );

    // Remove Gutenberg theme.
    wp_dequeue_style( 'wp-block-library-theme' );

    // Remove inline global CSS on the front end.
    wp_dequeue_style( 'global-styles' );
}, 20 );
copy

In the root directory open the wp-config.php file and add the following code before the "That's all, stop editing! Happy publishing" comment. It will disable Theme Editor in the Admin area located in Appearance section. To enable it again, change the Bool attribute to false.

#wordpress#php
define('DISALLOW_FILE_EDIT', true);
copy

In the root directory open the wp-config.php file and add the following code before the "That's all, stop editing! Happy publishing" comment. It will disable Theme Editor in the Admin area located in Appearance section and the options to update Themes and Plugins in the CMS. To enable it again, change the Bool attribute to false.

#wordpress#php
define('DISALLOW_FILE_MODS', true);
copy

Use do_shortcode function to output WordPress shortcodes in the code.

#wordpress#php
echo do_shortcode('[your_shortcode]');
copy

In the root directory open the wp-config.php file and add the following code before the "That's all, stop editing! Happy publishing" comment. Next, login to your WordPress admin panel and go to Tools > Network Setup to configure it.

#wordpress#php
define('WP_ALLOW_MULTISITE', true);
copy

You can enable post and page revisions by adding the following line before the "That's all, stop editing! Happy publishing" comment in the wp-config.php file. If the attribute is set to 'true' WordPress will store all revisions for the posts. Setting it to 'false' will deactivate revisions altogether. Finally, you can pass a positive integer to set the maximum number of stored revisions.

#wordpress#php
define( 'WP_POST_REVISIONS', true ); // true|false|integer
copy

Enqueue WordPress dashicons to frontend. By default dashicons are only available in the admin area. Add the following code to the functions.php file to use WordPress icons anywhere in your website.

#wordpress
function enqueue_dashicons() {
   
   wp_enqueue_style( 'dashicons' );

}
add_action( 'wp_enqueue_scripts', 'enqueue_dashicons' );
copy

esc_html is a method allowing you to escape html from a string passed as an attribute.

#wordpress#php
$copy = "Text <span> with some html </span>."
/* Returns 'Text with some html'.

$escapeHtml = esc_html($copy);
/* Returns: 'Text <span> with some html </span>'.
copy

esc_attr_e prints and escapes translated text.

#wordpress#php
esc_attr_e('Some text');
copy

esc_url is a function cleaning up a url. It escapes and cleans special characters.

#wordpress#php
esc_url('./some/url/to/escape.html');
copy

Using get_bloginfo lets you access information about your site. Pass an argument to return name, description, wpurl, url, admin_email, charset, version, html_type, text_direction, language, stylesheet_url, stylesheet_directory, template_url, pingback_url and more.

#wordpress#php
print get_bloginfo('description');
copy

Returns path to the child theme directory and the location of the style.css file.

#wordpress#php
get_stylesheet_directory_uri();
copy

get_post returns an object holding information about the post. By passing an argument you can access object arguments and return the data. Available data - ID, post_author, post_date,post_date_gmt, post_content, post_title, post_excerpt, post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_content_filtered, post_parent, guid, menu_order, post_type, post_mime_type and comment_count.

#wordpress#php
get_post('ID');
copy

Helper function displaying post's content.

#wordpress#php
the_content();
copy

Run the following code to quickly get and display all post meta data.

#wordpress#php
print_r( get_post_meta( get_the_ID()));
copy

Lets you load a partial element to a page. If the same partial is provided with a child theme it will override the parent theme file.

#wordpress#php#template
get_template_part( 'partial/header' );
copy

The following methods allow for getting and displaying translated text in your theme.

#wordpress#php
// Get text
__( 'Your text', 'text_domain' );

// Get text with a specified context
_x( 'Your text', 'Form label', 'text_domain' );

// Echo out text
_e( 'Your text', 'text_domain' );

// Use translated text inside of sprintf method
echo sprintf('This is %s in a paragraph', __( 'your text', 'text_domain' )); 
copy

get_the_ID returns am ID of a current item in the loop.

#wordpress#php
echo get_the_ID();
copy

Get theme author declared in the main stylesheet document.

#wordpress#php
wp_get_theme()->get( 'Author' );
copy

Get template name declared in the main stylesheet document.

#wordpress#php
wp_get_theme()->get( 'Template' );
copy

Get version of the theme declared in the main stylesheet document.

#wordpress#php
wp_get_theme()->get( 'Version' );
copy

This method lets you check if post is associated with a specific tag. First attribute expects the tag slug, the second taxonomy slug.

#wordpress#php#tag#taxonomy
has_term( 'some-tag', 'my-taxonomy' );
copy

Check if the given page is a 404.

#wordpress#php#template
if( is_404() ) {
    echo "Ups, page not found!";
}
copy

Check if an admin panel or a dashboard is opened.

#wordpress#php#template
if( is_admin() ){
    echo "Admin active";
}
copy

Check if the admin bar is showing.

#wordpress#php#template
if( is_admin_bar_showing() ) {
    echo "Admin bar is active";
}
copy

Check if the given page is a blog index.

#wordpress#php#template
if( is_blog() ){
    print "Blog home";
}
copy

Check if the given page is set to be front page.

#wordpress#php#template
if( is_front_page() ){
    echo "Homepage";
}
copy

Check if the given page is a WordPress page type.

#wordpress#php#template
if ( is_page() ) {
    print "This is a page";
}
copy

Check if page is using a template.

#wordpress#php#template
if ( is_page_template( 'about.php' ) ) {
    print "This page is using About template";
}
copy

Check if the given page is a search results page.

#wordpress#php#template
if ( is_search() ) {
    echo "Search";
}
copy

Check if the given page is a single blog post type.

#wordpress#php#template
if ( is_single() ) {
    echo "Single post";
}
copy

Returns page used in the wp-admin area.

#wordpress#php#global-variable
global $pagenow;
copy

Helper function for displaying the post thumbnail. Default Wordpress image sizes - thumbnail|medium|medium_large|large|full. Default WooCommerce image types - shop_thumbnail|shop_catalog|shop_single.

#wordpress#php
the_post_thumbnail( 'thumbnail' ); // thumbnail|medium|medium_large|large|full
the_post_thumbnail( 'shop_thumbnail' ); // shop_thumbnail|shop_catalog|shop_single
copy

WordPress loop iterates through the_post object allowing you to get the post data.

#wordpress#php
<?php while ( have_posts() ) : the_post(); ?>

        <?php the_content(); ?>

<?php endwhile;
wp_reset_query();?>
copy

This function returns a html number pagination in the template. Note, it doesn't work with custom post types.

#wordpress#php
the_posts_pagination();
copy

Lets you register a script in the functions.php file to be called from another part of your site. For example you can register a javascript file for the gallery component and only enqueue it in the page if the gallery component has been used.

#wordpress
// Register script in functions.php file
function register_gallery_script(){
	wp_register_script('galleryjs', get_stylesheet_directory_uri() . '/path/to/gallery.js', array(), '1.0', true);
}
add_action( 'wp_enqueue_scripts', 'register_gallery_script' );

// Call the script from the component
wp_enqueue_script('galleryjs');    
copy

Set a global variable as part of the functions.php file.

#wordpress#php
// Add this function in function.php file

function set_some_global_variable() {
    global $some_variable;
    $some_variable = 1;
}
add_action( 'after_setup_theme', 'set_some_global_variable' );

// Than, it can be used in other parts of the theme

global $some_variable;

echo $some_variable;
copy

This filter lets you change compression level when saving and uploading jpeg files. By default compression level is set to 90.

#wordpress#php
function change_jpeg_quality() {
    return 95; 
}
add_filter( 'jpeg_quality', 'change_jpeg_quality');
copy

Useful helper function for displaying category title on the archive pages.

#wordpress#php
single_cat_title();
copy

Returns the excerpt post content. By default it returns up to 55 words.

#wordpress#php
the_excerpt();
copy

Prints a link to a page or a post.

#wordpress#php
the_permalink();
copy

Print post's or page's title.

#wordpress#php
the_title();
copy

This handy functions will append a trailing slash to a given string. First it strips all slashes from the end of the url and then adds one to avoid double-slashing.

#wordpress#php
$url_to_slash = 'https://shortcode.dev/wordpress-cheatsheet';
trailingslashit($url_to_slash); // returns: 'https://shortcode.dev/wordpress-cheatsheet/'
copy

Get gallery images data array - src [0] - width [1] - height [2] - and if resized [3].

#wordpress#php#woocommerce#image
global $product;
$product_image_ids = $product->get_gallery_attachment_ids();

foreach( $product_image_ids as $product_image_id ) { 
	$prod_image = wp_get_attachment_metadata($product_image_id);

	print_r(wp_get_attachment_image_src($product_image_id, 'thumbnail'));				
	print_r(wp_get_attachment_image_src($product_image_id, 'medium'));				
	print_r(wp_get_attachment_image_src($product_image_id, 'medium_large'));

} ?>
copy