admin管理员组

文章数量:1287598

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

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
Add a comment  | 

1 Answer 1

Reset to default 0

Javascript 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