Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define and use helper functions in theme functions.php?

Tags:

php

wordpress

How to get following to work properly in Wordress Theme functions.php file?

I haven't figured out how to make the top function available to the bottom function within the theme's functions.php file. I'm not grasping how to setup hooks so they can work together. Thank you.

Filter/helper/whateveryoucallit function:

function poohToPee( $pooh_log )
{
  switch( $pooh_log )
  {
    case 'gross-poop':
      $pee_equivalent = 'Grossest of Pees';
    break;
    case 'ok-poop':
      $pee_equivalent = 'Bland Snack Pee';
    break;
    case 'shang-tsung-plop':
      $pee-equivalent = 'Random U-Stream';
    break;
  }
  return $pee_equivalent;
}

Ajax handler function:

function screw_loose()
{
  if( isset($_REQUEST['pooh_log']) )
  {
    echo poohToPee( $_REQUEST['pooh_log'] );
  }
}
add_action('wp_ajax_priv_screw_loose', 'screw_loose')
like image 575
James Huckabone Avatar asked Dec 23 '13 07:12

James Huckabone


Video Answer


1 Answers

The add_action usually calls the function you are passing through at the point that hook is called.

Since you are using some sort of ajax hook are you really able to make sure your function isn't being called? It wouldn't be echo-ing anything out to the screen since it is running in the background.

Normally any function you define in functions.php is readily available to use within the theme.

It is obviously normally best to organize and have classes, in which case you'd pass the method to the hook as an array, for example add_action( 'admin_init', array( $this, 'someFunction' ) ); and that add_action I just did would be put in the __construct function of the class.

For instance you could do this:

class helloWorld
{
    function __construct()
    {
        add_action( 'admin_init', array( $this, 'echoItOut' ) );
    }

    function echoItOut()
    {
        echo 'Hello World';
    }
}

$helloWorld = new helloWorld;

Alternatively you could also do this:

class helloWorld
{
    function echoItOut()
    {
        echo 'Hello World';
    }
}

$helloWorld = new helloWorld;

add_action( 'admin_init', array( $helloWorld, 'echoItOut' ) );

Or simply:

function echoItOut()
{
    echo 'Hello World';
}

add_action( 'admin_init', 'echoItOut' );

If you put any of these blocks of code I provided in your functions.php file and go to your Dashboard you will see 'Hello World' printed out at the top under the admin bar most likely (might vary from theme to theme if the dashboard has custom styling).

like image 97
Todd Nestor Avatar answered Nov 05 '22 05:11

Todd Nestor