Blog

05 Mar
2013

WordPress Icon Logo

Adding a custom function in WordPress


You may want to add your own custom functions to your WordPress theme files. The following example is a very simple echo 'hello world!', but if you are using the built in WordPress functions it can be very powerful.

1. First go into your themes folder (wp-content/themes/YOURTHEME/functions.php) and open the functions.php file.

2. Then add your custom function like the example below.

// THE FUNCTION //
function output_hello_world() {
    return 'hello world!';
    // why use return instead of echo? It allows you to place the output exactly where you need it. Echo will place it at the top of the content //
}

// ADD THE ACTION/FUNCTION TO CALL IN A TEMPLATE FILE //
add_action('call_hello_world', 'output_hello_world');

// ADD THE SHORTCODE/FUNCTION TO CALL IN A POST //
add_shortcode( 'post_hello_world', 'output_hello_world' );

3. Now you can call the function in a template file such as wp-content/themes/YOURTHEME/content.php.

<?php 
    // Call your custom function //
    do_action( 'call_hello_world' ); 
?>

Or in a post direct in the CMS with:

    // Call your custom function //
    [post_hello_world]
Posted in: < CMS >
me@grafxflow avatar

me@grafxflow


I am a Full-stack Developer who also started delving into the world of UX/UI Design a few years back. I blog and tweet to hopefully share a little bit of knowledge that can help others around the web. Thanks for stopping by!

Visitors also viewed these posts


Add comment

Add comment