This question already has an answer here: Get post meta in enqueued js file (1 answer) Closed 3 years ago.admin管理员组文章数量:1287598
i have post meta named 'product_price'. If this post meta is called in php it can be written:
<?php echo get_post_meta($post->ID, 'product_price', true); ?>
How to get this post meta 'product_price' in themedir/js/script.js file?
Please help me masters. thank you
This question already has an answer here: Get post meta in enqueued js file (1 answer) Closed 3 years ago.i have post meta named 'product_price'. If this post meta is called in php it can be written:
<?php echo get_post_meta($post->ID, 'product_price', true); ?>
How to get this post meta 'product_price' in themedir/js/script.js file?
Please help me masters. thank you
Share Improve this question asked Sep 27, 2021 at 10:42 rasyidrasyid 11 bronze badge 2- no, my post meta in single.php. I want to call this post meta 'product_price' in my .js file – rasyid Commented Sep 27, 2021 at 10:56
- No it's not. Post meta isn't "in" a template. The linked answer and comments are what you want. – Jacob Peattie Commented Sep 27, 2021 at 10:58
1 Answer
Reset to default 0Javascript cannot directly call PHP functions...
We need JS as well as PHP
JS will send ajax request as soon as document is ready, you need to specify postid yourself..
jQuery(document).ready(function(){
jQuery.ajax({
url : "/wp-admin/admin-ajax.php",
type: "POST",
data: {'action': 'PriceAJAX', 'postid': 12345},
success: function(response) {
Price = response['Theme'];
});
});
Once it is done, the PHP will kick in, and find the post meta for your specified ID...
function PriceAJAX(){
$ID = $_POST['postid']
$Price = get_post_meta($ID, 'product_price', true);
$Data = array('Price' => $Price);
wp_send_json($Data);
wp_die();
}
add_action( 'wp_ajax_nopriv_PriceAJAX', 'PriceAJAX');
add_action( 'wp_ajax_PriceAJAX', 'PriceAJAX' );
本文标签: javascriptHow to Get Post Meta in Js File
版权声明:本文标题:javascript - How to Get Post Meta in .Js File 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741299287a2370998.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论