get php variable from functions php and echo it in theme template files

This may seem like a silly question but I cannot figure this out.

I’ve created a variable in my functions.php – and I’m trying to echo it in my template files.

I’m guessing it’s because of scope.

What’s the simpliest what to echo a variable or create a function to allow me to output this facebook ID in various template files.

This is what I’ve currently got in my functions.php…

$fb_app_id = '68366786876786';

And this is how I was trying to echo it…

<?php echo $fb_app_id; ?>

Any ideas would be hugely helpful, thanks you very much

Solutions Collecting From Web of "get php variable from functions php and echo it in theme template files"

If you don’t have access to the value, it’s likely a scope issue. Make sure you globalize it first:

global $fb_app_id;
echo $fb_app_id;


I’m not a fan of global variables, so the alternative I recommend is using WordPress’ built-in filter mechanism. You add the filter in your functions.php file and apply it where needed.

In functions.php:

add_filter( 'fb_app_id', 'return_fb_app_id' );
function return_fb_app_id( $arg = '' ) {
    return '68366786876786';

In your template files:

echo apply_filters( 'fb_app_id', '' );

Or use an action hook

In functions.php

add_action( 'fb_app_id', 'echo_fb_app_id' );
function echo_fb_app_id() {
    echo '68366786876786';

In your template files:

do_action( 'fb_app_id' );

Whether you use an action hook or a filter is entirely up to you. I recommend a filter because it can return a value. This is far more flexible than just injecting echo calls in your template.

I would use WordPress options in this case. You can set an option using either add_option() or update_option() (probably better for your case). You would use update_option('fb_app_id', '68366786876786'); somewhere in you’re functions.php file (the init hook function would probably be a good place).

You could then show this option in your theme files using echo get_option('fb_app_id');

The reason I would suggest this way, rather than using globals (ick) or action/filter hooks is that if you plan on releasing your theme to the public, it will be much easier to make fb_app_id an editable option in a theme options page.

the easiest way would be to just create a callable function, you don’t really need a hook here

function get_fb_app_id() {
    $fb_app_id = '68366786876786';
    return $fb_app_id;

and in the template:

echo get_fb_app_id();