0

I create a plugin to quick payment.

When user click button Quick pay. It show popup call views/display-popup.php.

In this file, I declare variable $post.

<?php
    global $post;
    $id = $post->ID;
    $name = get_the_title();
?>

Ok, it will get $id and $name values and show.

On function.php, I call it:

add_action( 'woocommerce_share', 'fun_add_link_below', 50 );
function fun_add_link_below()
{
    global $post;
    if(absint($post->ID) > 0){
        require(ROOTDIR . '/views/display-popup.php');
    }
}

Problem is:

I create a new file have name ajax-send-email-save-database.php.

This file also needs using $post variable to update my database.

<?php
add_action('wp_ajax_ajax_cart_send_mail','ajax_cart_send_mail');
add_action('wp_ajax_nopriv_ajax_cart_send_mail','ajax_cart_send_mail'); 
function ajax_cart_send_mail(){
    global $post;
    $id = $post->ID;
    $name = get_the_title();
}
?>

But I receive values of $id and $name is null.

Update:

My js ajax file:

$('input#submit-order-quick_view').on('click', function(event) {
    event.preventDefault();
    var content = '';
    var data_details = {
        'action': 'ajax_cart_send_mail',
        'hoten': getdata(frm,'hoten'),
        'sdt': getdata(frm,'sdt'),
        'email': getdata(frm,'email'),
        'diachinhan': getdata(frm,'diachinhan'),
        'product_title' : product_title,
    }

    $.ajax({
        url: product_ajax.url,
        type: 'POST',
        dataType: 'text',
        data: data_details,
    }).done(function(data) {
        console.log(data);
    }).fail(function() {
        console.log("Error");
    });
}
2

$post isn't set in an admin-ajax.php request because you're not querying for any post or inside a loop. In your script that sends the ajax request you'll need to send the post ID and retrieve a post object in the callback:

function ajax_cart_send_mail(){
    $post = get_post( $_POST['post_id'] );

    $id = $post->ID;
    $name = $post->post_title;
}
add_action('wp_ajax_ajax_cart_send_mail','ajax_cart_send_mail');
add_action('wp_ajax_nopriv_ajax_cart_send_mail','ajax_cart_send_mail'); 
3
  • I tried with $post = get_post( $_POST['post_id'] ); or $post = get_post( $_POST['id'] );. But when I var_dump($post). Variable $post still null. – vanloc Sep 15 '17 at 6:06
  • 2
    You need to send the post id in the ajax request, you can't pull it out of the ether. – Jacob Peattie Sep 15 '17 at 6:12
  • I'm the newbie in Wordpress. Can you add more code? I updated my Ajax file. So sorry about that, I have the problem at this too long times. – vanloc Sep 15 '17 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.