Only execute jQuery function(on document ready) on the page has shortcode from plugin [duplicate]

What I eventually want to do is when user logged-in to the site, I want to redirect the to the page with all the post created by that user and I want to load them via AJAX request.

I have save shortcode that will have all posts from current user.

function ajax_write_here(){
    $output="<div id="write_here_ajax_wrap"></div>";
    return $output;
}
add_shortcode('write-here-ajax', 'ajax_write_here');

And have php function hooked to AJAX request

function write_here_ajax_dashboard() {
    echo "test";
}
add_action( 'wp_ajax_write_here_get_posts', 'write_here_ajax_dashboard' );

jQuery function in Document ready

jQuery(document).ready( function($) {
    function write_here_list_page(){
        $.ajax({
            type: "GET",
            url: ajax_object.ajax_url, // check the exact URL for your situation
            dataType: 'html',
            data: {
                action: 'write_here_get_posts',
                security: ajax_object.ajax_nonce
            },
            error: function(jqXHR, textStatus, errorMessage) {
                console.log(errorMessage);
                return false;
            },
            success: function(data) {
                //console.log(data);
                $('#write_here_ajax_wrap').html('');
                $('#write_here_ajax_wrap').append(data);
            }

        });
    }
    // Initiate function
    write_here_list_page();
});

Problem I have now is the jQuery function is being triggered all the pages through out the site. How do I make it only triggered on the page has the Shortcode inserted?

1 Answer
1

You can wp_enqueue_script in your shourtcode. Here are the code I fixed.

Register your JS file

function wh_enqueue() {
    wp_register_script( 'wh-ajax-app', WH_PATH . '/js/write-here-ajax.js', array('jquery'), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'wh_enqueue' );

and enqueue in your shortcode function

function ajax_write_here(){
    wp_enqueue_script( 'wh-ajax-app' ); // Enqueue your script here
    $output="<div id="write_here_ajax_wrap"></div>";
    return $output;
}
add_shortcode('write-here-ajax', 'ajax_write_here');

This will only load your JS file on the page has shortcode inserted.

Leave a Comment