7

I have created a function in my plugin myplugin with the name foo, how to call it from the frontend?

 e.g. index.php?
  • 2
    hmmm a 25% acceptance rate is pretty low – Tom J Nowell Nov 18 '12 at 20:24
  • 1
    How to call a PHP function within a PHP file is a PHP question, not a WordPress question. – Chip Bennett Nov 19 '12 at 11:57
  • 1
    its literally a question about wordpress plugins @ChipBennett .... – nick Nov 28 '15 at 0:38
12

The same way you would any other:

foo();

Active plugins are loaded before the theme files

You may want to check that your plugin is activated and the function is available so things dont go pear-shaped if you forget to activate it, like:

if(function_exists('foo')){
    foo();
} else {
    echo "oh dear you haven't activated/installed 'myplugin', go do that before the 'foo' feature is available";
}

Also keep in mind foo is a very generic function name, perhaps the "omgfoo" plugin also has a foo function. So prefix/namespace your function to something unique

You will eventually want to use actions and filters, as they're safer and better practice, you can continue to read up on that here

5

You don’t. A Theme should not rely on a plugin except in a very controlled environment. Use actions and filters instead.

So in your theme you might use:

do_action( 'before_header' );

… or …

$bg_options = array (
    'wp-head-callback' => 't5_custom_background_frontend',
    'default-color'    => 'f0f0f0',
    'default-image'    => '',
);
$bg_options = apply_filters( 't5_theme_bg_options', $bg_options );
add_theme_support( 'custom-background', $bg_options );
add_action( 'login_head', $bg_options['wp-head-callback'] );

In your plugin you use add_action() and add_filter() to change or add new content. This way the theme will still work when the plugin has been deactivated and you don’t have to use function_exists().

2

Active plugins are loaded (as in technically - their files are included and processed by PHP during WordPress load) by the time theme templates run.

So your function should be available and can be called as any other function:

<?php foo(); ?>

for example.

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.