Last active
May 12, 2021 19:31
-
-
Save wvfitzgerald/237c0822d1973ad378ac27c6f415ecbb to your computer and use it in GitHub Desktop.
Example of WordPress Ajax on the front end
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /*---We can add this bit to to our theme's fuction.php or a cusotm pluging-----*/ | |
| function get_wp_posts() { | |
| // Arguments: see docs for get_post @ https://developer.wordpress.org/reference/functions/get_posts/ | |
| $args = array( | |
| 'post_type' => 'post', | |
| 'post_status' => 'publish', | |
| 'numberposts' => 5, | |
| ); | |
| // Get the Post | |
| $wpajaxposts = get_posts( $args ); | |
| echo json_encode( $wpajaxposts ); | |
| exit; | |
| } | |
| /*---- The important part-AJAX action hooks for both logged in and non-logged in users, | |
| notice that the firstparmaeted is our function ame prepended wiht wp_ajax_ and | |
| wp_ajax_nopriv_ , | |
| -----*/ | |
| add_action('wp_ajax_get_wp_posts', 'get_wp_posts'); | |
| add_action('wp_ajax_nopriv_get_wp_posts', 'get_wp_posts'); | |
| /* Where our ajax magic happens, for this I am using wp_footer to add my js but we can add the js to a page template, | |
| widget etc. */ | |
| function get_ajax_post_js(){ ?> | |
| /*----Handle this as usual with the " data: { action : 'get_wp_posts' }" bit refferncing our above funciton-------*/ | |
| <script> | |
| jQuery.ajax({ | |
| type: 'POST', | |
| url: '<?php echo admin_url('admin-ajax.php');?>', | |
| dataType: "json", // add data type | |
| data: { action : 'get_wp_posts' }, | |
| success: function( response ) { | |
| jQuery.each( response, function( key, value ) { | |
| console.log( value.post_title ); // the posts titles. | |
| // console.log( key, value ); //Uncomment to see all of the past data | |
| } ); | |
| } | |
| }); | |
| </script> | |
| <?php | |
| } | |
| add_action('wp_footer' , 'get_ajax_post_js'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment