Retrieving Wordpress Custom Posts Via Ajax

in #utopian-io9 years ago (edited)

Quick Brief

If you are not familiar with some of the terms in the title, a quick brief:
Wordpress: is one of the top open source solutions available for building websites/web solutions. It initially started as a blogging platform and became a huge content management system, allowing for practically almost any web solution/functionality to be implemented.
Custom Posts: due to the growth of wordpress, and since its initial purpose was to be a blogging platform, its key object structure was considered to be a post, just like this one, but it also allowed -
moving forward - for the creation of custom post types, which can basically be any object that you need to use in your solution, a book, a car, a bank,...
Ajax: is a communication approach built over Javascript, and that allows asynchronous communication between the front end (what your visitor sees), and the server side (where your server code and database are run)



image.png
Image created by my own

What we are planning to do?

One of the essential functionalities that might be needed on a front end development work would be dynamically grabbing a list of custom post types, making those available for front end, and performing additional functionality onto them.
In order to do that, we need to create both back end (PHP) and front end(JS/JQuery) scripting allowing the proper communication and then data manipulation or display as needed. Those can be created within a single PHP file, as php files can allow dynamic generation of content and rendering this to the front end.
Let us proceed..


Back end script

The below back end script, in PHP, allows you to first hook your function into wordpress' AJAX calls mechanism, and then, once an AJAX call is received, the code within will be executed, looping through the custom post type instances, and encode those in proper JS format, to be returned upon success to the front end AJAX call.

//hooks required to perform the connection between AJAX calls and php function
add_action( 'wp_ajax_nopriv_filter_matching_cpts', 'filter_matching_cpts' );
add_action( 'wp_ajax_filter_matching_cpts', 'filter_matching_cpts' );
/* function handling the generation and response back to the AJAX call/front end
function filter_matching_cpts(){
    //perform a query to grab the instances of the custom post type
    $args = array( 
            'post_type' => 'cpt', 
            'post_status'    => 'publish',
            'posts_per_page' => -1
        );
    $loop = new WP_Query( $args );
    $cpt_array = array();
    //loop through the results
    while ( $loop->have_posts() ) : $loop->the_post();
        $cpt_array[] = array(
                    'title' => $loop->post->post_title,
                    'meta_data' => get_post_meta($loop->post->ID),
                );
    endwhile;
    wp_reset_query();
    //encode the data into a format acceptable by JS
    echo json_encode($cpt_array);
    //kill the process to return properly without additional 0
    die();
}

We will also need to make sure, that the AJAX variable is well localized to be used on the front end interface, this is accomplished via hooking into the wp_enqueue_scripts and running a wp_localize_script to make it available

//enqueue ajax url
function gk_cstm_enqueue() {
    wp_localize_script( 'ajax-script', gk_cstm_calc',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'gk_cstm_enqueue' );

Front end script

The below front end script is basically a Javascript / AJAX call, which allows, upon a specific action, or simply upon site load for fetching of the custom post type instances, and then displaying their content or performing any needed manipulations upon!

<script>
    var mortgage_plans;
    //perform the AJAX call
    jQuery(document).ready(function($){
        $.ajax({
            type: "POST",
            dataType: "json",
            url: gk_cstm_calc.ajax_url,
            custom_data: 'custom_data',
            data: {
                'action'                :   'filter_matching_cpts',
                'custom_data'           :   custom_data,
            },
            success: function(data){
                //perform action on received data
                console.log(data);
                mortgage_plans = data;
                jQuery.each(mortgage_plans, function(index, plan){
                    //do some action here
                    console.log(data['title']);
                }
                //or simply render the content into an HTML field
                jQuery('#data_content').empty().html(data);
            }
        });
    });
</script>

Full Code - Gist

You can also check out the full script on my GIST link here

That's basically it! Hope you found this as helpful as intended !

@mcfarhat



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

I've been waiting for custom posts for over a year!

glad to be of help, @reddust ! :)

Thank you for the contribution. It has been approved.

[utopian-moderator]

Thank you !

thank you
good information

Hey @mcfarhat I am @utopian-io. I have just super-voted you at 17% Power!

Achievements

  • I am a bot...I love developers... <3
  • Much more informative than others in this category. Good job!
  • You have less than 500 followers. Just gave you a gift ;)
    Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by mcfarhat from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews/crimsonclad, and netuoso. The goal is to help Steemit grow by supporting Minnows and creating a social network. Please find us in the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.079
BTC 63100.12
ETH 1669.66
USDT 1.00
SBD 0.41