0

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()) {
        // REGISTER/ENQUEUE OTHER SCRIPTS...
        $mathjax = get_post_meta($post->ID,'mathjax',true);
            if($mathjax == 'y'){
                wp_enqueue_script('mathjax');
            }
    }
}

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

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

<?php
add_action( 'init', 'enqueue_conditionally' );
function enqueue_conditionally(){
    $mathjax = get_post_meta( get_the_ID(),'mathjax',true);
    if($mathjax == 'y'){
        wp_enqueue_script('mathjax');
    }
}
?>

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

3
  • 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
    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
    Jul 26, 2015 at 6:57
  • updated my answer according to your new info. 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.