The functions.php file lets you add custom features and change how your WordPress site works without changing core files.
0
0
Functions.php role in Wordpress
Introduction
You want to add new features like custom menus or widgets to your WordPress theme.
You need to change default WordPress behavior, like modifying how posts display.
You want to add custom PHP code that runs with your theme.
You want to register new styles or scripts to load on your site.
You want to create custom shortcodes for easier content formatting.
Syntax
Wordpress
<?php
// Add your PHP functions here
function my_custom_function() {
// Your code
}
add_action('init', 'my_custom_function');The file must start with <?php and contain only PHP code.
Use WordPress hooks like add_action or add_filter to connect your functions.
Examples
This code adds a new menu location called 'Header Menu' to your theme.
Wordpress
<?php
// Register a custom menu
function register_my_menu() {
register_nav_menu('header-menu', 'Header Menu');
}
add_action('init', 'register_my_menu');This enables featured images for posts in your theme.
Wordpress
<?php // Add support for post thumbnails function add_theme_supports() { add_theme_support('post-thumbnails'); } add_action('after_setup_theme', 'add_theme_supports');
This shortcode
[year] shows the current year anywhere in your posts or pages.Wordpress
<?php
// Create a shortcode to display current year
function display_year() {
return date('Y');
}
add_shortcode('year', 'display_year');Sample Program
This code creates a shortcode [greeting] that shows a welcome message wherever you put it in your content.
Wordpress
<?php
// functions.php example
// Add a custom greeting shortcode
function custom_greeting() {
return 'Hello, welcome to my site!';
}
add_shortcode('greeting', 'custom_greeting');OutputSuccess
Important Notes
Always back up your functions.php before editing to avoid site errors.
Errors in functions.php can break your site, so test changes carefully.
Use child themes to add custom code without losing changes when updating the main theme.
Summary
functions.php is your themeβs place to add custom PHP code.
It helps you add features, change behavior, and create shortcodes.
Always use WordPress hooks to connect your functions safely.