When I Update a Wordpress Theme Do I Need to Create the Menus Again

Learning to create custom WordPress themes opens upwardly a whole new world for y'all to explore. It allows you lot to build custom designs for yourself, your clients and even contribute dorsum to the open-source community.

In this guide, we're going to take you from cipher to having a fully functional theme that tin can be submitted to the WordPress.org theme directory.

To follow along you volition need a basic understanding of HTML, CSS, PHP, and how WordPress works.

All the lawmaking used in this guide volition be available for reference in this Github repository.

Table of Contents:

  1. Creating essential files for your custom theme
  2. Create functions.php
  3. Add template parts
  4. Add atypical.php, archive.php, search.php, and 404.php
  5. Ancillary files
  6. Create page templates
  7. Make your theme uniform with RTL.css
  8. Ever follow all-time practices
  9. Distribute your WordPress theme
  10. Examination and amend code

Step #1: Creating Essential Files for Your Custom Theme

A functioning WordPress theme can consist of just two files: style.css and index.php. This is possible considering of WordPress's template hierarchy.

When WordPress outputs a webpage it searches for the near specific template available, if a template doesn't exist it will motion down the bureaucracy until information technology finds 1 that does. Here's a applied instance:

The user is on https://example.com/practical-example, which is a page. WordPress will endeavour to locate a template in this order:

      • page-{slug}.php – The folio slug is /practical-instance, WordPress will wait to use your-theme/folio-practical-example.php
      • folio-{id}.php – The folio ID is 42, WordPress will look to utilize your-theme/folio-42.php.
      • page.php – WordPress will attempt the general-purpose your-theme/page.php template.
      • singular.php – The singular template can render Posts and Pages, so it's tried subsequently the more specific page.php
      • index.php – Lastly your-theme/index.php is used if no other template is found.

Let'due south start by building a theme with just the essential files and then we can layer on more than features as we explore how they piece of work.

In /wp-content/themes/, create a binder named my-custom-theme and create these two following files:

fashion.css

For WordPress to recognize our theme and output it properly in the Advent → Themes list we demand to place some WordPress-specific code at the pinnacle of style.css, it looks like this:

/* Theme Name: My Custom Theme Theme URI: https://yourwebsite.com/theme Author: Your Name Author URI: https://yourwebsite.com Description: This is my kickoff custom theme! Version: 1.0.0 License: GNU Full general Public License v2 or afterward License URI: <https://www.gnu.org/licenses/gpl-2.0.html> Text Domain: my-custom-theme Tags: custom-groundwork */          

Technically none of the fields are required, but if yous desire your theme to look good in wp-admin then they are highly encouraged. They are besides required if yous are distributing your theme on WordPress.

      • Theme Proper noun – You should always supply a theme name. If you don't then the binder name volition be used, my-custom-theme in our example.
      • Theme URI – If used, the theme URI should provide a link to a folio where visitors can learn more about the theme.
      • Author – Your proper noun goes here.
      • Writer URI – A link to your personal or business website tin exist placed here.
      • Description – The description is shown on the wp-admin theme modal and also on the WordPress theme listing.
      • Version – Version numbers help developers keep track of changes and let users know if they are using the latest version. Nosotros follow the SemVer numbering system to denote the severity of changes in an update.
      • License – How you license your theme is up to yous, but if you choose a not-GPL-compatible license then you won't be able to distribute your theme on WordPress.
      • License URI – This is but a link to the license listed higher up.
      • Text Domain – The text domain is used when translating your theme into other languages. Don't worry we will explore this in-depth later on. For at present, it's plenty to know that information technology's a skilful practice for the theme folder and the text-domain to be the theme name separated by hyphens instead of spaces.
      • Tags – Tags are merely used if you are uploading your theme to the WordPress.org theme directory. They are the basis of the 'Feature Filter' machinery.

Copy and paste the above into mode.css and you lot volition accept something like this:wp-admin theme information

Notation: It looks a little bare at the moment every bit we don't have a screenshot yet. We will add that later.

index.php

index.php is the only other strictly required file. Its chore is to return all the front-finish output for our theme.

Since index.php is going to be rendering all of our pages (home, posts, categories, archives) it's going to be doing a lot of work. To commencement we demand a caput section that will cover the HTML basics.

<!DOCTYPE html> <html <?php language_attributes(); ?>>   <head>     <meta charset="<?php bloginfo( 'charset' ); ?>">     <meta name="viewport" content="width=device-width, initial-scale=one">     <link rel="contour" href="https://gmpg.org/xfn/11">     <?php wp_head(); ?>   </head>

This is standard HTML with ane exception, [wp_head()](<https://programmer.wordpress.org/reference/hooks/wp_head/>). wp_head is a core function that allows WordPress and 3rd-party plugins to insert code into the header without modifying your template files. This is called an activity hook.

If you are familiar with HTML you may notice there isn't a <title> tag to output the page title. That'south because WordPress can use the wp_head claw to dynamically insert the title.

Some other use of wp_head is to enqueue styles (.css) and scripts (.js). There are very good reasons for doing this instead of hardcoding them, which we volition expect at afterwards on.

Next, nosotros take the trunk of the folio:

<trunk <?php body_class(); ?>>

body_class() is a helper role provided by WordPress that will output a listing of useful CSS classes which describe the page existence displayed such equally:

            class="page page-id-2 page-parent page-template-default logged-in"                      

body_class(); also accepts a parameter so you can add your own classes, for example:

<body <?php body_class( 'wide-template blueish-bg' ); ?>>

Next, we take the template header.

<header class="site-header"> 	<p class="site-championship"> 		<a href="<?php echo esc_url( home_url( '/' ) ); ?>"> 			<?php bloginfo( 'name' ); ?> 		</a> 	</p> 	<p course="site-description"><?php bloginfo( 'description' ); ?></p> </header><! – .site-header – >          

Here we are using WordPress' built-in template functions to output the Site Championship and Description. We've also used a helper part, home_url(), to link the Site Championship back to the homepage.

Next upwards, the torso of the folio:

<div class="site-content"> 	<?php 	if ( have_posts() ) : 	 		while ( have_posts() ) : 	 			the_post(); 			?> 	 			<article <?php post_class(); ?>> 			 				<header class="entry-header"> 					<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> 				</header><! – .entry-header – > 			 				<div grade="entry-content"> 					<?php the_content( esc_html__( 'Continue reading &rarr;', 'my-custom-theme' ) ); ?> 				</div><! – .entry-content – > 			 			</article><! – #post-## – > 			 			<?php 			// If comments are open or we have at to the lowest degree one comment, load upwardly the comment template. 			if ( comments_open() || get_comments_number() ) : 				comments_template(); 			endif; 	 		endwhile; 	 	else : 		?> 		<article class="no-results"> 			 			<header class="entry-header"> 				<h1 form="page-title"><?php esc_html_e( 'Nothing Found', 'my-custom-theme' ); ?></h1> 			</header><! – .entry-header – > 		 			<div grade="entry-content"> 				<p><?php esc_html_e( 'It looks like nothing was found at this location.', 'my-custom-theme' ); ?></p> 			</div><! – .entry-content – > 		 		</article><! – .no-results – > 	<?php 	endif; 	?> </div><! – .site-content – >          

This is where it gets interesting (and a bit more complex). Here we are using the most important characteristic of WordPress, the Loop. The loop does the difficult piece of work of figuring out which page the user is on and what should be shown. Information technology then returns a list of one or more 'posts' that nosotros can loop through and output information using template functions.

If the Loop doesn't return whatever results, for example on a 404 page or deleted post, nosotros use an else operator to show a predefined message.

Without any of the surrounding code, a simplified loop looks like this:

if ( have_posts() ) : // check if the loop has returned whatsoever posts.  	while ( have_posts() ) : // loop through each returned post. 		the_post(); // set upwardly the content and then we can use template tags similar the_title(). 		the_title(); // output the mail service title. 		the_content(); // output the postal service content. 	endwhile;  else :   	echo 'No Page Found'; // output an fault message if at that place are no posts.  endif; ?>          

Annotation: Because WordPress has its origins in blogging, a lot of functions use the 'mail service' terminology, even though they can return and output any type of content (posts, pages, custom mail service types).

Lastly, nosotros take the footer, all we need to practise here is close the HTML tags nosotros opened earlier. There'southward another action hook, wp_footer(), which is actively used by WordPress and plugins to include scripts in the footer needed to return the page.

<?php wp_footer(); ?> 	</body> </html>          

If you've been post-obit along so far you lot will have a fully functional WordPress theme that looks like this:

starter theme preview

Our theme is not going to win any pattern awards (it has no CSS) and it's missing a lot of features that users consider essential (sidebars, navigation, metadata, thumbnails, pagination, etc.) but it's a great get-go!

Let's continue on and see how we can improve information technology.

Step #2: Create functions.php

Functions.php is not strictly a required file, but information technology provides so many benefits that 99.99% of themes have it. In functions.php you can utilize WordPress' born theme functionality and also add together your own custom PHP lawmaking.

Create a functions.php in your theme folder now every bit we will be adding lawmaking to it in the adjacent sections.

Adding a Navigation Card

Well-nigh, if not all websites utilize a navigation carte du jour, but upwardly to now our theme doesn't support one. To tell WordPress our theme features a navigation menu, nosotros must annals it in functions.php similar this:

register_nav_menus( array(     'menu-ane' => __( 'Primary Menu', 'my-custom-theme' ), );          

Note: register_nav_menus() accepts an assortment so you can register more than one card if needed.

WordPress at present knows almost our menu, just we notwithstanding need to output information technology in our theme. We do that past adding the post-obit lawmaking beneath the site description in alphabetize.php:

wp_nav_menu( array(     'theme_location' => 'bill of fare-1', ) );          

Now we have an (unstyled) navigation bill of fare:

starter theme with nav menu

Adding a Sidebar

Our theme doesn't have a sidebar (widget area) either, let'southward ready that now.

Kickoff, we need to register the sidebar in functions.php:

function my_custom_theme_sidebar() {     register_sidebar( array(         'name' => __( 'Chief Sidebar', 'my-custom-theme' ),         'id'   => 'sidebar-i',     ) ); } add_action( 'widgets_init', 'my_custom_theme_sidebar' );          

Now create sidebar.php in your theme binder and add together the post-obit code:

<?php if ( is_active_sidebar( 'sidebar-ane' ) ) { ?>     <ul class="sidebar">         <?php dynamic_sidebar('sidebar-1' ); ?>     </ul> <?php } ?>          

Here we are using an if statement to check if the sidebar is 'active' before we output the lawmaking. An active sidebar is 1 that the user has added at least i widget to.

The last step is to include the sidebar in index.php, above wp_footer() add a get_sidebar() phone call.

Adding Featured Images

Like sidebars and navigation menus, nosotros can't just output featured images in our theme and look them to work, we must tell WordPress we support that feature first. In functions.php add:

add_theme_support( 'post-thumbnails' );

Now we can add the_post_thumbnail(); within our loop and the thumbnails will work. The but problem is that they volition output at WordPress's maximum size of 1920px x 2560px, which is also big for most uses. Luckily WordPress has some other helper office: add_image_size();

When a user uploads an prototype, and if prototype size is divers, WordPress will generate a version of the uploaded image at that size (while keeping the original). If the user's image is smaller than the dimensions you lot've set WordPress will practice cypher as information technology tin can't make an image bigger than the original.

To use an optimized feature image rather than the original, identify the following lawmaking in functions.php:

add_image_size( 'my-custom-image-size', 640, 999 );

The first parameter is the handle, the 2nd is the image width and the 3rd is the tiptop. Both summit and width are optional in case you only want to limit i dimension.

In index.php:

the_post_thumbnail( 'my-custom-image-size' );

Enqueueing Styles and Scripts

Earlier we stated that information technology'due south better to enqueue styles and scripts rather than hardcoding them directly into the template files. That's considering enqueuing allows for a lot more flexibility.

When done correctly, enqueuing as well tells WordPress which resources are being loaded. When WordPress knows which resource are needed it can brand sure the same resource isn't being loaded more than than once. This is especially important when you lot take an extremely pop library like jQuery or FontAwesome that multiple themes and plugins will be utilizing.

Another benefit of enqueuing is that a resource that is enqueued can be dequeued past a plugin, avoiding the need to change template files.

Although our theme has a style.css file it isn't using it all the same, let's enqueue that now:

function my_custom_theme_enqueue() {     wp_enqueue_style( 'my-custom-theme', get_stylesheet_uri() ); } add_action( 'wp_enqueue_scripts', 'my_custom_theme_enqueue' );          

get_stylesheet_uri() is a helper function that retrieves the URI of the current theme's stylesheet. If nosotros were enqueueing any other file nosotros would need to do this instead:

wp_enqueue_style( 'my-stylesheet', get_template_directory_uri() . '/css/style.css' );          

Our theme doesn't take any scripts, if it did nosotros would enqueue them similar this:

function my_custom_theme_enqueue() { wp_enqueue_style( 'my-custom-theme', get_stylesheet_uri() ); wp_enqueue_script( 'my-scripts', get_template_directory_uri() . '/js/scripts.js' ); } add_action( 'wp_enqueue_scripts', 'my_custom_theme_enqueue' );

An exception to the to a higher place is scripts that have been pre-registered by WordPress, in those cases you lot only need to supply the first parameter ($handle):

wp_enqueue_script( 'jquery' );

Calculation Fashion With CSS

Our theme has strong foundations only lacks whatever design, adding some bones CSS to style.css volition brand a huge divergence. We've added around ~100 lines of CSS to our sample theme equally a demonstration and the consequence looks like this:

starter theme with css

Title Tag

All themes should utilize WordPress's built-in functionality to generate the title tag, which is enabled by adding this code to your functions.php file: add_theme_support( 'title-tag' ); That's all in that location is to it, WordPress will handle the output of the page <championship> and if needed plugins can modify the output using filters. SEO plugins ofttimes do this in an try to further optimize the titles.

Step #3: Add together Template Parts

Right now 80% of our template code is in index.php.

While this works it will effect in a lot of code repetition when we take other template files such every bit singular.php, search.php, and archive.php. Template Parts make theme development easier past allowing us to re-apply lawmaking across templates. Every bit our header and footer volition be the same on every page they are a perfect candidate for using template parts. Start, create header.php and motility the following code from alphabetize.php:

<!DOCTYPE html> <html <?php language_attributes(); ?>> 	<head> 		<meta charset="<?php bloginfo( 'charset' ); ?>"> 		<meta name="viewport" content="width=device-width, initial-calibration=1"> 		<link rel="profile" href="<https://gmpg.org/xfn/11>"> 		<?php wp_head(); ?> 	</head>   <header class="site-header">     <p class="site-championship">       <a href="<?php echo esc_url( home_url( '/' ) ); ?>">         <?php bloginfo( 'name' ); ?>       </a>     </p>     <p class="site-clarification"><?php bloginfo( 'description' ); ?></p> 	<?php 	wp_nav_menu( array(     	'theme_location' => 'bill of fare-i', 	) ); 	?>   </header><! – .site-header – >          

In alphabetize.php replace the to a higher place code with:

<?php get_template_part( 'header' ); ?>          

Note: When getting a template office, you must omit the .php from the template role handle.

Adjacent, create a footer template role by moving this code to footer.php and repeating the above process:

<?php wp_footer(); ?> 	</body> </html>          

Lastly, we'll move the 'no-results' code to a template part likewise, as information technology's likely to be used in multiple templates. Create content-none.php and move this code to the new file.

<commodity course="no-results">    <header class="entry-header">     <h1 class="folio-title"><?php esc_html_e( 'Aught Plant', 'my-custom-theme' ); ?></h1>   </header><! – .entry-header – >    <div class="entry-content">     <p><?php esc_html_e( 'It looks similar cipher was found at this location.', 'my-custom-theme' ); ?></p>   </div><! – .entry-content – >  </commodity><! – .no-results – >          

Your index should now look like this:

<?php get_template_part( 'header' ); ?>   <div class="site-content">     <?php     if ( have_posts() ) :       while ( have_posts() ) :          the_post();         ?>          <article <?php post_class(); ?>>  		  <?php the_post_thumbnail(); ?>            <header class="entry-header">             <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>           </header><! – .entry-header – >            <div class="entry-content">             <?php the_content( esc_html__( 'Go along reading &rarr;', 'my-custom-theme' ) ); ?>           </div><! – .entry-content – >          </article><! – #mail-## – >          <?php         // If comments are open or we take at least i comment, load up the comment template.         if ( comments_open() || get_comments_number() ) :           comments_template();         endif;       endwhile;      else :       get_template_part( 'content-none' );     endif; 	?> 	</div><! – .site-content – > <?php get_sidebar(); get_template_part( 'footer' );          

While the above will piece of work perfectly, there is a slight improvement we can make. WordPress has helper functions for including the header, footer and sidebar template parts. As it's a best exercise to use core functionality where possible we should employ those instead.

Replace get_template_part( 'header' ); with get_header(); and get_template_part( 'footer' ); with get_footer();

Step #4: Add singular.php, archive.php, search.php, and 404.php

The groundwork we completed with template parts will pay dividends as we add new template files to our theme. Below we've listed the virtually mutual. To avoid overwhelming you lot with code examples nosotros've linked to the source code on Github instead.

atypical.php

Posts and Pages, when shown on their ain URLs, are considered 'Singular' as most of the time the layout will be the same for both of these folio types. Just in the result that it isn't you can use the more specific page.php and single.php (postal service) instead.

Case Code – singular.php

archive.php

Annal templates commonly differ from atypical templates in two ways: they bear witness excerpts rather than the full content and feature an archive header explaining the content.

Refer back to the template bureaucracy and you will see that the archive template covers all types of archives (writer, category, tag, taxonomy, engagement) if this doesn't work for your employ-instance you lot can still apply the more specific templates:

      • author.php
      • category.php
      • tag.php
      • taxonomy.php
      • date.php

Example Code – archive.php

search.php

WordPress websites tin can be searched using the ?s= URL parameter, for example, yourwebsite.com?s=examination. The search.php template outputs the results of those searches.

Example Code – search.php

404.php

The else statement we added in index.php catches "page not found" errors, but you may want to decouple that functionality into its own template file to have more command over the output. That'south the use-case of the 404.php template file.

Instance Lawmaking – 404.php

Step #5: Ancillary Files

If you lot are distributing your theme to the public then the post-obit files are imperative. Without these, your theme will go rejected from theme repositories and marketplaces.

screenshot.png

The screenshot is shown in the wp-admin themes list when the user is selecting a new theme. Here are some best practices you lot should follow:

      • Screenshots should exist 1200px x 900px
      • Screenshots should exist in .png or .jpg format
      • Screenshots should be an authentic representation of the theme
      • Screenshots should exist optimized (utilize tinypng.com or similar)

readme.txt

WordPress doesn't use any information from readme.txt, information technology pulls everything information technology needs from fashion.css. On the other hand, the WordPress theme directory does pull of import information from the readme file and considers it a required file.

Most developers apply readme.txt every bit the key location to store all the information about their theme. A uncomplicated readme.txt looks like this:

=== Theme Name === Requires at least: v.0 Tested up to: 5.two Requires PHP: 5.six License: GPLv2 or later License URI: <https://www.gnu.org/licenses/gpl-ii.0.html>  Short description. No more than than 150 chars.  == Clarification == Theme desc.  == Changelog ==  = 1.0 = * Added new option  == Resources == * normalize.css <https://necolas.github.io/normalize.css/>, (C) 2012-2016 Nicolas Gallagher and Jonathan Neal, [MIT](<https://opensource.org/licenses/MIT>)          
      • Requires at to the lowest degree – This is the minimum version of WordPress that your theme is compatible with.
      • Tested up to – This field denotes the almost recent version of WordPress your theme has been tested with.
      • Requires PHP – This field denotes the minimum version of PHP your theme will function on.
      • Description – This description field is non currently displayed anywhere.
      • Changelog – The changelog is non used anywhere, only developers and some users volition reference this file to meet what changes take been fabricated.
      • Resource – Nigh third-political party resources require attribution of some sort. The resources department is a widely-accepted identify to put those. Even for resources that don't explicitly require attribution, it'south still a good practice to list them hither so users are aware of the licenses of resource they are using.

Pace #6: Create Page Templates

Page Templates allow developers to create custom templates that can be used for individual posts and pages. For example, most themes have a 2-column (content – sidebar) layout but on some pages, the user might want to just focus on the content and not show a sidebar. That's where a folio template can help.

How are "Folio Templates" created?

In our theme folder, create a new folder named 'page-templates' and within that folder create a file called single-column.php. To speed things up copy all the code from singular.php to page-templates/unmarried-column.php and remove the call to get_sidebar() equally this template won't need that.

At present we need to add a special header that tells WordPress this is a folio template, it looks similar this:

/* Template Name: Single Column Template Template Post Blazon: postal service, folio */          

The code is cocky-explanatory, we are only telling WordPress the name of the template and which post types it can be used with.

That'south all there is to it, our new page template is now available in the editor under 'Folio Attributes'.

page template dropdown

Step #7: Brand Your Theme Compatible with RTL.css

Non all languages read left to right. Arabic and Hebrew, for instance, are read from Right to Left (RTL). In that location's a simple mode to make your theme uniform with RTL languages.

Create a new file in your theme binder called rtl.css, then copy and paste the following code:

body { 	direction: rtl; 	unicode-bidi: embed; }          

If an RTL language is the agile linguistic communication on a WordPress website, WordPress knows to load this CSS file automatically.

This is a very basic implementation of RTL functionality to get you started. If you are interested in learning more hither are two fantastic resource:

Right to Left Language Support Documentation

Twenty Twenty RTL code

Step #8: Always Follow Best Practices

Best practices have evolved over time to make edifice and maintaining WordPress themes easier. Not only will post-obit these principles assistance you but they will besides get in easier for other developers when they need to work with your code.

1) Employ Starter Themes

Starter themes provide a solid base for yous to build your theme upon. Typically they are lightweight, contain footling to no styling and no configuration options. Over time you lot might build your own starter theme which yous tin can base of operations all your projects on, just for now here are some popular options:

      • Underscores
      • Scaffold
      • HTML5 Bare

2) Go to Know WordPress Coding Standards

Coding standards are a mode of formatting your lawmaking in a consistent manner across the entire codebase. WordPress has coding standards for HTML, CSS, Javascript, and PHP. While using a coding standard has no effect on the end-user experience, information technology does make your code a lot more readable. Even if yous don't use the WordPress coding standards, we'd always recommend using a standard.

      • WordPress.org Coding Standards
      • WPCS
      • PHP Coding Standards

3) Use Localization

Thank you to the difficult work of volunteers, WordPress is available in hundreds of languages. If your theme is going to exist released publicly it needs to be built in a style that allows it to be translated as well.

Don't worry, it'southward super easy to do. All we need to exercise is make sure that all strings are passed through a 'localization office' rather than beingness output direct.

Instead of this:

<?php echo 'Previous Post'; ?>

We practise this instead:

<?php echo __( 'Previous Mail', 'my-custom-theme' ); ?>

__() is a localization part that accepts a string and a text-domain. The function returns a translation of the string provided, or the original string if a translation isn't available.

4) Avoid Plugin Functionality

When a user changes the theme, only the presentation layer should change. The content and functionality should stay mostly the same. What this means is that whatever office that affects how WordPress roles should be contained in a plugin, not your theme. Some examples of plugin functionality include:

      • Custom Post Types
      • Page Builders
      • Social Media Sharing
      • Search Engine Optimization (SEO)

While it may seem convenient (and possibly a selling point) to include SEO controls in a theme, it really hurts the user in the long term. In the time to come, they volition need to change their theme only tin can't considering all of their SEO configurations are tightly coupled to the current theme. In contrast, if the configurations were stored in a plugin they could alter theme without worrying.

5) Prefixing (Preclude Conflicts)

To forestall conflicts, all functions, classes and global variables created by your theme should exist prefixed. This is important because it'due south incommunicable to know what other code is running on your user's website. Prefixing prevents name clashes and fatal errors.

Your theme'south name separated by dashes or underscores volition work as a prefix most of the fourth dimension. If the theme name is very long the initials tin can piece of work instead.

Theme Name: Scaffold  form Scaffold_Class {} function scaffold_function() {} global $scaffold_global  Theme Proper name: My Long Theme Name  class MLTN_Class {} function mltn_function() {} global $mltn_global          

6) Utilise Core Functionality

Where it exists, you should e'er use core functionality equally opposed to reinventing the wheel. This includes, just is not limited to Sidebars, Navigation Menus, Post Thumbnails, Custom Headers, and Custom Backgrounds. These features take been battled-tested by millions of users and are actively maintained and improved upon.

If you need to change the functionality or output of a core function then information technology's possible using one of the many hooks and filters WordPress offers. For instance wp_nav_menu() has a 'walker' parameter so you can have complete control of the output.

7) Escaping and Sanitizing Data

As a theme programmer, you must be familiar with escaping and sanitizing data to protect your users from potential exploits.

Escaping

Escaping is the procedure of checking data is safe before it'south output and sanitizing is checking data before it'due south saved to the database.

WordPress has helper functions that you tin can utilize to escape information and then you don't demand to build those yourself. esc_html is one instance of an escaping function. This is what an unescaped output looks like:

            echo get_theme_mod( 'error_page_title' );          

To escape the output we do this:

            echo esc_html( get_theme_mod( 'error_page_title' ) );          

Some other escaping functions you should be enlightened of are esc_attr(), absint(), esc_url().

It's likewise possible to translate and escape a string using a single function:

            echo esc_html( __( '404 Not Institute', 'my-custom-theme' ) );          

Becomes:

echo esc_html__( '404 Not Constitute', 'my-custom-theme' ); // or esc_html_e( '404 Not Plant', 'my-custom-theme' );          

Tip: Anywhere in your theme where y'all have echo $ you should check if it needs to be escaped, it usually does.

Sanitizing

If you add settings to your theme, you lot need to make sure the data that users input to those settings is safe before it enters the database. WordPress has a number of functions to help with sanitizing input.

When adding a setting to your theme using the Customizer API it has a parameter for called 'sanitize_callback' which accepts the name of a sanitization function. Any input the setting takes is checked past the office you lot provide to 'sanitize_callback' before it enters the database.

Information technology highlights the importance of sanitization that if even one of your settings is missing the sanitize_callback information technology won't be accustomed into the WordPress theme directory.

$wp_customize->add_setting(      'my_custom_theme_setting',      array(         'sanitize_callback' => 'sanitize_text_field' // A core sanitization function.     ) );          

An official listing of sanitization and escaping functions can exist seen here: Data Sanitization/Escaping

Step #9: Distribute Your WordPress Theme

Themes can be distributed via dissimilar channels depending on the result you lot want to accomplish. If your outcome is to simply contribute to the open up-source community and then there'due south no better fashion to practice that than to upload your theme to the WordPress directory. If instead, you are looking to sell your theme and brand coin directly, in that location are means to do that too.

Here are the leading websites for theme distribution:

one) WordPress.org (Best identify to become downloads and users)

The master benefit of hosting your theme on WordPress is that you lot go a visibility boost from your theme being seen not only on the wordpress.org website simply also in the wp-admin dashboard.

Another benefit of hosting your theme with WordPress is the congenital-in update system. If yous update your theme all users will be notified inside their wp-admin dashboards and given an easy path to update to the latest version.

WordPress.org only accepts free themes, but that doesn't mean you tin't brand money. A free theme tin be a great aqueduct for promoting your premium theme, plugin or service.

2) WordPress.com

WordPress.com hosts both free and premium themes. However, they oasis't been open to new author submissions for a few years now.

iii) ThemeForest

ThemeForest is the leading marketplace for premium themes. The top-selling theme (Avada) has sales in excess of $5,000,000.

Generally speaking the buyers on Theme Forest expect full-featured "multi-purpose" themes. All of the top themes have folio builder functionality and are supported by teams of developers. It's a very hard market to suspension into for new authors.

4) Creative Market and Mojo Marketplace

Artistic Market place And Mojo Marketplace are minor players in the premium themes marketplace which is why we grouped them together. They both effectively offer the same service as ThemeForest but on a smaller calibration.

five) Github

Github is the easiest manner to brand your free theme public. There's no review procedure and no guidelines to follow. Nevertheless, you won't do good from the visibility of wordpress.org and volition demand to build your own update mechanism for users to get the latest versions.

Step #10: Test and Improve Code

i) Testing Your Theme

Theme Unit Test

The Theme Unit of measurement Examination is a standard WordPress content import file that contains a broad range of content types and edge cases. It's easy to upload to your development surround and volition highlight a lot of scenarios yous may accept disregarded.

WP_DEBUG

As a theme developer, testing your theme with WP_DEBUG enabled is the bare minimum y'all should be doing. Your theme should return no errors or warnings when WP_DEBUG is set to true.

It's also important to repeat the test with the different PHP versions your theme supports. With each major PHP release, there are new changes, warnings, and depreciation. It's not uncommon for a theme to exist error-free on PHP5.6 only show errors on PHP7.

To enable WP_DEBUG, add the following code to wp-config.php:

DEFINE( 'WP_DEBUG', true );          

Monster Widget

Monster Widget is a helpful plugin that lets you lot add 13 core widgets to your sidebar at once. The core widgets use a variety of HTML elements which makes them perfect for testing your theme.

Theme Sniffer

The Theme Sniffer is a plugin created past the Theme Review Squad (TRT). Information technology catches a lot of (only not all) escaping and localization errors. Information technology also checks your theme against the WordPress coding standards.

2) Submitting Your Theme to WordPress.org

At the first of this guide, we said that past the time yous reached the cease you would have a theme you could submit to wordpress.org. Let's look at that process.

Upload Process

The upload procedure is simple. Create or login to your WordPress account and then navigate to this folio – https://wordpress.org/themes/upload/

Yous could zip your theme and upload information technology right now, just here are some things you lot might want to know first.

Requirements

The Theme Review Squad (TRT) has a strict set of requirements. Your theme volition not be accepted into the directory until it meets all the requirements.

Review Process

When you upload a theme, at that place is a two-stage review procedure information technology must pass before it tin be accepted into the directory.

First, an automatic check is performed every bit soon as you printing Upload. Behind the scenes, the automated checker works in a very similar manner to the Theme Sniffer plugin. If it finds any errors it volition reject the theme and the upload process ends there.

If your theme passes the automated bank check then it joins a queue of themes waiting for a human review. The human review is completed by volunteers from the TRT. The number of themes in the queue far exceeds the number of reviewers, which means it can frequently take 2-three months for your theme to reach the front of the queue.

It'southward imperative that your theme is error-free and complies with all the requirements by fourth dimension it reaches the human review stage as if it has more than 3 meaning errors it tin be rejected. If a theme is rejected at the human review stage it must rejoin the queue at the back, which means waiting 2-3 months over again for another human review.

Useful Resource: The Well-nigh Common WordPress Theme Development Mistakes (and How to Fix Them)

It'due south worth noting that the TRT is ever looking for new reviewers, volunteering tin be a great learning feel and a way to contribute to the open-source community.

3) Your Theme Listing

Congratulations, your theme has been canonical! You at present have your own list that looks like this.

Here'south an overview of what you lot can expect to see on this page:

      • Screenshot – The screenshot is the first affair potential users run into so make it as highly-seasoned as possible. Simply remember information technology must nonetheless be an accurate representation of the theme and not a photoshop render. Accept inspiration from the almost pop themes.
      • Clarification – The description which is pulled from style.css is an platonic place to describe your theme and it's key features. It besides helps to listing recommended or required plugins here. The description doesn't support any formatting (bold, italic, hyperlinks) or even line breaks.
      • Tags – This is a representation of the tags you lot listed in fashion.css. Only these tags here are accepted.
      • Preview Button – The preview is generated by wordpress.org and every bit theme developers, we have no command over the output. Unfortunately, as the previewer uses basic content and no configuration information technology often results in a less than perfect preview.
      • Theme Homepage Link – The URL for the Preview push is pulled from the 'Theme URI' field in your fashion.css. There are strict requirements that this URL must only be used to brandish a page displaying information about your theme.
      • Active Installations – This is the number of websites actively using the theme. The number is rounded to the nearest ten, hundred or thousand. It'southward not possible to call back an exact number.
      • Downloads Per Day – This is how many times your theme has been downloaded. A 'Download' can exist a new download or a theme update.
      • Reviews – For a user to leave a review they must be logged in to a wordpress.org account. Generally speaking, reviews are hard to get unless you explicitly inquire your users to submit them.
      • Support – The built-in support platform is swell for managing and resolving bug with your theme. The user must be logged in to create a support thread.
      • Translations – The translation platform is a fantastic resource. If you have been post-obit the advice throughout this guide to localizing your theme and so your users will be able to translate it into other languages and expand your potential user base beyond simply English language speaking users.

iv) Updating Your Theme

When yous make changes to your theme in the futurity and need to update the version hosted on WordPress the process is unproblematic.

First update the 'Version:' field and changelog in readme.txt. And then goose egg the file and re-upload it using the same upload folio as before.

The organisation will recognize it as an update and will automatically approve it so that it doesn't require another human review.

fixrunner advertisement
Advertisement

melendezwastrame.blogspot.com

Source: https://websitesetup.org/wordpress-theme-development/

0 Response to "When I Update a Wordpress Theme Do I Need to Create the Menus Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel