开发者

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?


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.


Custom field values are stored in your database, therefore, you can't access them via jQuery unless you've made it available to the resulting HTML markup somehow.

If you're thinking of using custom field values in your jQuery/JS, I'd go about it by modifying my theme to actually spout the values I need directly on the markup. You could use hidden INPUT fields for that, or maybe even flushing the values directly on some script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜