1

Is it possible to call a function from functions.php in custom page or blog post?

I put simple function in functions.php:

function testTest()
{
echo "Test";
}

And called it from the page:

<?php testTest();?>

But it doesn't work. Do I need to make a plugin to use simple function like that inside one chosen custom page?

Thanks for your answer, Mary

1

You could use add_shortcode if you want to use it within the editor.

function footag_func() {
    return "Test";
}
add_shortcode( 'footag', 'footag_func' );

And then use [footag] in your editor.

Or

Use code like this in functions.php and add a conditional tag

add_action( 'loop_start', 'your_function' );
function your_function() {
if ( is_singular('post') ) {
    echo 'Test';
    }
}

or

Create a function in functions.php

function your_function() {
return 'Test';

}

And then use this in your template

echo your_function();
| improve this answer | |
  • 1
    Thanks a lot! I will check all of the versions. I upvoted, but unfortunately it doesn't show because I'm a new user. Thanks once again! – Mary Jul 2 '19 at 9:08
1

You can quickly create a quick shortcode for doing that.

add_shortcode( 'test_shortcode', 'my_test_callback' );

Then, in the callback function you do this:

function my_test_callback() {
    //start adding the echoed content to the output buffer
    ob_start();

    //run your code here - in this case your testTest() function
    testTest();

    //return the output buffer
    //NOTE: directly echoing the content will give unexpected results
    return ob_get_clean();
}

Then, in your content pages you just add [test_shortcode] and it will run your PHP function.

For a better view on shortcodes here are some useful links:

Official Shortcode API

A nice tool for creating shortcodes

An article I wrote on how to build shortcodes

| improve this answer | |
  • 1
    Thanks a lot! I will check that. I upvoted, but unfortunately it doesn't show because I'm a new user. – Mary Jul 2 '19 at 9:09
  • no worries. hope that helped :) – Cornel Raiu Jul 2 '19 at 9:10
  • Hi @CornelRaiu - Is there a way to create a normal link on frontend, that upon clicking, runs "test_shortcode" or "my_test_callback()" function? – Ramin Arabbagheri May 20 at 11:12
  • 1
    @RaminArabbagheri you should make use of AJAX for that. Make an on click listener on the button that will trigger an AJAX action and then output the response – Cornel Raiu May 20 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.