1. Home
  2. Docs
  3. WordPress Developer
  4. WordPress Theme Development
  5. Theme Functions

Theme Functions

The functions.php file is where you add unique features to your WordPress theme. It can be used to hook into the core functions of WordPress to make your theme more modular, extensible, and functional.

The functions.php file behaves like a WordPress plugin, adding features and functionality to a WordPress site. You can use it to call WordPress functions and to define your own functions.

Each theme has its own functions file, but only code in the active theme’s functions.php is actually run. If your theme already has a functions file, you can add code to it. If not, you can create a plain-text file named functions.php to add to your theme’s directory

Uses:

  • Use WordPress hooks. For example, with the excerpt_length filter you can change your post excerpt length (from default of 55 words).
  • Enable WordPress features with add_theme_support(). For example, turn on post thumbnails, post formats, and navigation menus.
  • Define functions you wish to reuse in multiple theme template files.
  • Enqueue theme stylesheets and scripts. See wp_enqueue_scripts.
  • Enable Theme Features such as Sidebars, Navigation Menus, Post Thumbnails, Post Formats, Custom Headers, Custom Backgrounds and others.
  • Define functions used in several template files of your theme.
  • Set up an options menu, giving site owners options for colors, styles, and other aspects of your theme.

Deciding when to add functions to functions.php or to a specific plugin: You may find that you need the same function to be available to more than one parent theme. If that is the case, the function should be created in a plugin instead of a functions.php for the specific theme. This can include template tags and other specific functions. Functions contained in plugins will be seen by all themes.

Examples

Setup

A number of theme features should be included within a “setup” function that runs initially when your theme is activated. As shown below, each of these features can be added to your functions.php file

if ( ! function_exists( mytheme_setup) ) :

function mytheme_setup() {

}

End If;

Navigation Menus

Custom navigation menus allow users to edit and customize menus in the Menus admin panel, giving users a drag-and-drop interface to edit the various menus in their theme.

register_nav_menus( array(

   ‘primary’   => __( ‘Primary Menu’, mytheme),

   ‘secondary’ => __( ‘Secondary Menu’, mytheme)

) );

Sidebar

Your site will include the widget-ready sidebar and comments sidebar after creating functional files.

Add the below code to functions.php :

<?php
if ( function_exists(‘register_sidebar’) )
   register_sidebar();
?>

. For More details View https://developer.wordpress.org/themes/basics/theme-functions/

Was this article helpful to you? Yes No

How can we help?