How to pass PHP variable in Wordpress to JSON file?

Viewed 247

I like to send specific data from a post to my JSON response in Wordpress. I like to send the output of the variable "hatus" to the JSON response, but it does not seem to work.

<?php echo wp_kses_post($hatus); ?>

And here is the code I am trying to send it to:

<?php

// Export API Data to JSON, another method
add_action('publish_post', function ($ID, $post) {

    $wp_uri = get_site_url();
    $customApiEndpoint = '/wp-json/wp/v2/posts'; // or your custom endpoint

    $url = $wp_uri . $customApiEndpoint; // outputs https://your-site.com/wp-json/wp/v2/posts

    $response = wp_remote_get($url);
    $responseData = json_encode($hatus); // saved under the wp root installation, can be customized to any folder

    file_put_contents('your_api_data_backup.json', $responseData);

}, 10, 2);
?>

What am I doing wrong here? The only thing I want is to show that 'hatus' variable outcome in my JSON response. Can you help?

1 Answers

You can send success JSON response by function wp_send_json_success() and error by wp_send_json_error(). Check documentation success and error.

But when you send a JSON response from PHP you should have a code that accepts it. For example when you send data by AJAX:

    $.ajax({
        url: '<?php echo admin_url( "admin-ajax.php" ) ?>',
        type: 'POST',
        data: 'your txt or array ',
        success: function( data ) {   
            alert( data );
        }
    });

Inside function "success" you get your JSON array from PHP.

Related