# How to load script conditionally on custom field in wp_postmeta?

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() {
// 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?

#### Solutions Collecting From Web of "How to load script conditionally on custom field in wp_postmeta?"

EDIT:
If you use $post in a function, you have to define it of course: function xyz(){ global$post;
}


<?php
$mathjax = get_post_meta( get_the_ID(),'mathjax',true); if($mathjax == 'y'){