Last active
May 20, 2020 01:03
-
-
Save kingjmaningo/fddd0be7b06db2f3464143af11f490b7 to your computer and use it in GitHub Desktop.
Simple post loop with Ajax. (Wordpress)
This file contains 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
jQuery(document).ready(function($){ | |
$('.my-posts').change(function(){ | |
var post_id = $('.my-posts').val(); | |
$.ajax({ | |
url : my_ajax_object.ajaxurl, | |
type : 'post', | |
data : { | |
action : 'get_data', | |
post_id : post_id, | |
}, | |
success: function(response){ | |
$('.my-retrieved-data').html(response); | |
} | |
}); | |
}); | |
}); |
This file contains 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 | |
// In your child theme's function, add these inside your wp_enqueue_scripts action if you havent enqueque/localized your scripts yet. | |
add_action( 'wp_enqueue_scripts', 'my_custom_enqueue' ); | |
function my_custom_enqueue() { | |
// Enqueue the file where your ajax code is saved | |
wp_enqueue_script( 'custom-ajax', get_template_directory_uri() . '/path/to/ajax.js' ); | |
// in JavaScript, object properties are accessed as my_ajax_object.ajax_url | |
wp_localize_script( 'custom-ajax-script', 'my_ajax_object', | |
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); | |
} | |
// In this example, we are trying to display the feature image | |
add_action( 'wp_ajax_get_data', 'get_data' ); | |
add_action('wp_ajax_get_data', 'get_data'); | |
function get_data(){ | |
$post_id = $_REQUEST['post_id']; | |
$post_image = get_the_post_thumbnail_url($post_id) ? : 'Oops no image yet!'; | |
echo $post_image; | |
die(); | |
} | |
// This is your shortcode | |
add_shortcode('my-shortcode','my_shortcode'); | |
function my_shortcode() { | |
ob_start(); | |
$args = array( | |
'post_type' => 'post', | |
'post_status' => 'publish', | |
); | |
$the_query = new WP_Query( $args ); ?> | |
<select class="my-posts"> | |
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> | |
<option class="mp-name mp-name-<?php echo get_the_ID(); ?>" value="<?php echo get_the_ID(); ?>" ><?php the_title(); ?></option> | |
<?php | |
wp_reset_postdata(); | |
endwhile; | |
?> | |
</select> | |
// This is where we will place the retrieved data based on your selection above. | |
<div class="my-retrieved-data"> | |
</div> | |
</php | |
return ob_get_clean(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment