javascriptjqueryajaxwordpresscall

Updating URL on ajax call


Trying to update url whenever the button for modal to show content is clicked, managed to find out how to change it but it returns http://localhost:3000/wp-admin/admin-ajax.php

which is not what I want, I want the normal blog post slug after my domain, any way I can achieve that dynamically? I'm using wordpress for this.

window.history.pushState(null, null, this.url);

Whole ajax.js

jQuery(function($) {

    $('body').on('click', '.view-post', function() {
        var data = {
            'action': 'load_post_by_ajax',
            'id': $(this).data('id'),
            'security': blog.security
        };
 
        $.post(blog.ajaxurl, data, function(response) {
            response = JSON.parse(response);
            $('#postModal h5#postModalLabel').text(response.title);
            $('#postModal .modal-body').html(response.content);
 
            var postModal = new bootstrap.Modal(document.getElementById('postModal'));
            postModal.show();

            window.history.pushState(null, null, this.url);

            
        });
    });
});

Solution

  • Found solution, so you have to store slug name in your callback function like this.

            // Get the post ID or some way to retrieve the post slug
            $post_id = get_the_ID(); // Example: Assuming you're inside a loop
    
            // Get the post slug
            $post_slug = get_post_field('post_name', $post_id);
            
            $arr_response = array(
                'title' => get_the_title(),
                'content' => get_the_content(),
                'post_slug' => $post_slug,
            );
    
    echo json_encode($arr_response);
    

    inside ajax js file you can extract post_slug and store it in the variable

            $.post(blog.ajaxurl, data, function(response) {
                response = JSON.parse(response);
                var postSlug = response.post_slug;
    
    
    window.history.pushState(null, null, postSlug);