WooCommerce: Get the post id in javascript code and pass it through ajax

倖福魔咒の 提交于 2021-01-28 05:07:59

问题


I need help figuring out how to get the product id from the product page, to my function that opens a model box after a vimeo video ends. inside that model box i need a variable with the product id. so i automatic can get the price of the product and insert the id inside a shortcode.

Hopefully someone can help, and feel free to ask, i will try to help if you need more information.

I have already tried the most common ideas, i could find.

global $product;
$id = $product->get_id();

or

global $post;
$id = $post->ID

or

global $product;
$id = $product->id;

I have tried in all the variations i could find.

if i use the first one, my function wont even work.

If i use the other 2, it only gives me a 0 as value.

// The javascript to call the function when video ends.
var iframe = document.querySelector("iframe");
var player = new Vimeo.Player(iframe);

    player.on("ended", function() {
      jQuery(document).ready(function($) {
    var data = {
        action: 'runThisPhpFunction',
    };

    jQuery.post(ajaxurl, data, function(popupfunction) {
        $("#popup-box").html(popupfunction);
    });
  });
});

Next up is my function.

//Call Javascript video vimeo script to functions

function add_my_scripts() {

        global $product;
        $deps = array('jquery');
        $in_footer = true;

            wp_register_script( 'myjavascript', get_stylesheet_directory_uri() . '/js/myjavascript.js', array(), '1.0.0', true );
          wp_enqueue_script( 'myjavascript', get_stylesheet_directory_uri() . '/js/myjavascript.js');
  }


add_action( 'wp_enqueue_scripts', 'add_my_scripts' );

add_filter( 'widget_text', 'do_shortcode' );
add_action( 'wp_ajax_runThisPhpFunction', 'runThisPhpFunction' );
add_action( 'wp_ajax_nopriv_runThisPhpFunction', 'runThisPhpFunction' );

global $wpdb;
global $wp;

// THE FUNCTION WHERE I NEED THE ID FROM CURRENT PRODUCT PAGE AUTOMATIC

function runThisPhpFunction() {
  global $product;
  $product = wc_get_product();
  $siteid = $product->ID;

    //echo '<script>console.log($product);</script>';
    echo '<script>document.getElementById("popup-box").classList.remove("hidden");</script>';
    echo '<div class="modalheader">';
    echo '<h3>Undskyld. Vi stoppede videoen!</h3>';
    echo '</div>';
    echo '<div class="modalcontent">';
    echo $siteid, 'Men vi venter lige her, klar til at fortsætte når du har hentet Dankortet 😉';
    echo '</div>';
}


回答1:


As you are using javascript/jQuery/Ajax and as you need to get the product ID (which is the Post ID) in your Javascript code to pass it through Ajax to PHP, try the following revisited code instead:

add_action( 'wp_footer', 'custom_vimeo_player_script' );
function custom_vimeo_player_script() {
    // Not in cart, checkout and my account pages
    if( ! ( is_checkout() || is_cart() || is_account_page() ) ) :
    ?>
    <script type="text/javascript">
    jQuery(function($){
        if (typeof wc_add_to_cart_params === 'undefined') 
            return false;

        var iframe = document.querySelector("iframe"),
            player = new Vimeo.Player(iframe);

        player.on('ended', function(){
            $.ajax({
                type: 'POST',
                url: wc_add_to_cart_params.ajax_url,
                data: {
                    'action': 'enable_vimeo_popup_box',
                    'the_id': <?php echo get_the_id(); ?>,
                },
                success: function (result) {
                    // if popup-box has the class hidden
                    if( $("#popup-box").hasClass('hidden') && result ){
                        // remove the class hidden and add the html output
                        $("#popup-box").removeClass('hidden').html(result);
                    }
                    console.log(result);
                },
            });
        });
    });
    </script>
    <?php
    endif;
}

// PHP: WordPress Ajax function triggered by Javascript
add_action( 'wp_ajax_enable_vimeo_popup_box', 'enable_vimeo_popup_box' );
add_action( 'wp_ajax_nopriv_enable_vimeo_popup_box', 'enable_vimeo_popup_box' );
function enable_vimeo_popup_box() {
    if( isset($_POST['the_id']) ){
        $post_id = (int) $_POST['the_id'];

        echo '<div class="modalheader">
        <h3>' . __("Undskyld. Vi stoppede videoen!") . '</h3>
        </div><div class="modalcontent">' .
        '<em>(post_id er ' . $post_id . ')</em> ' .
        __("Men vi venter lige her, klar til at fortsætte når du har hentet Dankortet 😉") .
        '</div>';
    }
    die();
}

Code goes in function.php file of your active child theme (or active theme). It should works.



来源:https://stackoverflow.com/questions/55633032/woocommerce-get-the-post-id-in-javascript-code-and-pass-it-through-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!