resonantdoghouse
6/24/2017 - 7:50 PM

WP Localize and AJAX.phtml


<?php

add_action( 'wp_enqueue_scripts', 'cptjs_enqueue' );

function cptjs_enqueue(){

	wp_register_script( 'cptjs_ajax', plugins_url('/js/ajax.js', __FILE__ ), array( 'jquery' ) );
	wp_enqueue_script( 'cptjs_ajax' );

	wp_localize_script( 'cptjs_ajax', 'API_TEST', array(
		'api_url' => esc_url_raw( rest_url() )
	));

}

?>

<script type="text/javascript">
jQuery(document).ready(function($){

    var results_container = '#remote-posts';

    $('#load-remote-posts').click(function(e){
        e.preventDefault();
        $.ajax({
            method: "GET",
            url: API_TEST.api_url + 'wp/v2/cptjs/',

            success: function( posts ){
                console.log( posts );

                var html = '',
                    title = '',
                    content = '';

                $.each( posts, function( i, post ){
                    title = '<h5><a href="' + post.link + '">' + post.title.rendered + '</a></h5>';
                    content = '<p>' + post.content.rendered + '</p>';
                    html += title + content;
                });

                $( results_container ).append( html );
            }
        })

        $('#load-remote-posts').hide();

    });


});
</script>