Wordpress - acnorrisuk/coding-style-guide GitHub Wiki

All code should follow the Wordpress coding standards.

Templates

Template files should follow the naming conventions set out by the Wordpress template hierarchy.

All page templates should have a template name set at the beginning of the file

<?php
/*
Template Name: Full Width Page
*/
?>

The Wordpress template tags should be used to generate common page templates.

get_header();
get_footer();
get_sidebar();
get_search_form();

Custom templates (to be used on multiple pages) should be included with get_template_part()

Scripts

All styles and scripts should be included via wp_enqueue_scripts() in the functions.php file.

/* Enqueuing styles & scripts */
function theme_name_scripts() {
    wp_enqueue_style( 'style-name', get_stylesheet_uri() );
    wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/script.js');
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

Optional arguments can be added to wp_enqueue_script to enable the use of dependencies, version numbers (for cache busting) and whether the script should load in the head or footer.

/* my-script.js version 1.1 loading with jquery dependency in the footer */
wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery'), '1.1', true );

Any styles or scripts which are intended to be conditionally loaded should be registered before being enqueued.

wp_register_script( 'vendor-script', 'https://domain.com/someScript.js');

Note: jQuery is loaded with Wordpress and does not need to be enqueued. A list of scripts which are loaded with Wordpress by default can be found here. When a script is enqueued which is dependent on jQuery, jQuery will run in noConflict mode. This means the common $ alias cannot be used and the full jQuery should be used instead. Alternatively, code can be placed inside a noConflict wrapper using using the $ shortcut.

jQuery( document ).ready( function( $ ) {
    // $() will work as an alias for jQuery() inside of this function
    [ your code goes here ]
} );

Security

All form data should be validated and sanitised before being submitted. For more information see the Wordpress Codex.

All output should be escaping using one of the built in Wordpress helper functions.

<!-- Escaping HTML -->
<h4><?php echo esc_html( $title ); ?></h4>

<!-- Escaping URLs -->
<img src="<?php echo esc_url( $great_user_picture_url ); ?>" />

<!-- Escaping HTML attributes -->
<ul class="<?php echo esc_attr( $stored_class ); ?>">

Note: Most Wordpress functions properly prepare data for output and don't need to be escaped again.

<h4><?php the_title(); ?></h4>
⚠️ **GitHub.com Fallback** ⚠️