I'm trying to tidy up some of the code that has been doing its job for quite a while. Specifically, I used to load scripts in header.php and I'm trying to move that into functions.php.

One of the scripts should be loaded only for pages with a certain value in wp_postmeta. Precisely, if and only if this table has the value true for meta_key "mathjax", the mathjax script should be loaded.

In header.php I used

function my_init() {
    if (!is_admin()) {
        $mathjax = get_post_meta($post->ID,'mathjax',true);
            if($mathjax == 'y'){

add_action('init', 'my_init');

Now, this code doesn't work in functions.php because $post is undefined. Can I still move this code into functions.php and if so, how can I make it work?

1 Answer 1


EDIT: If you use $post in a function, you have to define it of course:

function xyz(){
    global $post;
    //Your code

Initial answer, might help others: It appears to me, you do not use it inside an action or if so, you use it to early. It should work inside the 'init' action. So you could do something like

add_action( 'init', 'enqueue_conditionally' );
function enqueue_conditionally(){
    $mathjax = get_post_meta( get_the_ID(),'mathjax',true);
    if($mathjax == 'y'){

Ref.: https://codex.wordpress.org/Plugin_API/Action_Reference/init

  • sorry, I actually do use it in a function, followed by add_action but those lines didn't seem relevant to me. Please give me a few minutes to try and get your example running before I get back on that, ok?
    – RubenGeert
    Commented Jul 26, 2015 at 6:40
  • the good news is that I'm no longer getting an error. However, the script doesn't load with the if condition around it (but it does load after commenting out the if part). I inspected the DB whether mathjax is set properly and it is... Any idea what may cause that?
    – RubenGeert
    Commented Jul 26, 2015 at 6:57
  • updated my answer according to your new info. Commented Jul 26, 2015 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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