1

I am new to PHP and am building a WordPress theme. I would like to add a variable in the functions.php and use it in single.php as an if statement. At present, my single.php has the following code -

<?php 
  $prevPost = get_previous_post();
  $prevthumbnail = get_the_post_thumbnail($prevPost->ID, 'keepreading-thumb');

  if ( $prevPost ) : ?>
    <?php previous_post_link('%link',"$prevthumbnail"); ?>
    <h3><?php previous_post_link('%link'); ?></h3>
    <p><?php echo excerpt(25); ?></p>
  <?php endif; 
?>

I would like to have the $prevPost and $prevthumbnail variables to be defined in functions.php and would like to use them in an "if statement" in single.php.

P.S - I am a newbie in coding and would appreciate it if you can give me an answer in detail. Thank you...

1

either use global variable in functions.php:

    global $prevPost;
    $prevPost = 10;

in single.php :

    global $prevPost;
    if($prevPost)
     .. . . . Your code continues. .

Second method: define a function in functions.php and call that in single.php in functions.php :

    function func_prevPost(){
     $prevPost = 10;
     return $prevPost;
    }

in single.php :

    if(func_prevPost()){
    // your code here
    }
  • Thanks for the tip. I couldn't get the first one to work but the second one worked just fine. I am now using if(func_prevPost()){ and it works. But, I cannot get the thumbnail to show up. My actual code is $prevthumbnail = get_the_post_thumbnail($prevPost->ID, 'keepreading-thumb');. How can I add the $prevPost inside the above code. Also, how would I add it to the functions.php? Thank you... – Ajit Jun 21 '14 at 9:05
0

There are different ways to do that! This is easiest way:

Add your variables to a php files (e.g. config.php) and include it whenever you want to use its variables.

include('config.php');

Another easy way is using $_GET or $_POST variables.

$_GET['my_var']='123';

You can also define a global variable in functions.php.

global $my_var;
$my_var='123';

and then add global $my_var; before using it in single.php.

0

If I understand your question correctly, this code will only be used in single.php. Honestly I will stick with that code in single.php. Don't move it to functions.php and create a global varaible.

Globals might be useful at times, but I would advice you against adding variables to the global scope, unless you are using it itside a class or unless it is a really really necessarry. Globals in classes will only be accesible by that particular class.

Just a tip, if you ever add anything to the global scope, use names that no one will ever think of, never use names that will be easily replicated, as this might lead to a clash later on with plugins, even wordpress.

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.