Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress - Get Custom Field Value in jQuery

In wordpress is there any way that I can get the value of a custom field in jQuery?

like image 376
Sam Avatar asked Nov 28 '25 21:11

Sam


1 Answers

this should do the trick:

function my_jquery_var() {
    global $post;
    if ( $my_custom_field_name = get_post_meta( $post->ID, 'my_custom_field_name', 1 ) ) { 
        echo '<script type="text/javascript">var my_custom_field_name = "' . $my_custom_field_name . '";</script>' . "\n";
    }
}
add_action( 'wp_head', 'my_jquery_var' );

it hooks into the wordpress head, checks to see if the current post or page has a custom field called my_custom_field_name, if it does it spits out a var in java script that can then be used by jquery anywhere else.

It's tested and works.

like image 74
dwenaus Avatar answered Dec 01 '25 12:12

dwenaus