I am developing a website using WP CMS where I want to implement post title as drop-down list as well as when users select a drop-down title the content show below within reload. I am here. What will I do if I want to retrieve content by id?
function select_options(){ ?>
<form action="" method="POST">
<select name="count" id="selectId" >
<?php
$posts = new WP_Query(array('posts_per_page' => 3, 'post_type' => 'post'));
while($posts->have_posts()) : $posts->the_post(); ?>
<option id="selection" value="<?php echo get_the_ID(); ?>"><?php echo get_the_title(); ?></option>
<?php endwhile;
die()
?>
</select>
</form>
<?php
}
add_action('wp_ajax_select_option', 'select_options');
add_action('wp_ajax_nopriv_select_option', 'select_options');
Javascript:
jQuery(document).ready(function(){
jQuery.ajax({
//var count = $('#selection').val();
type: 'POST',
url: 'wp-admin/admin-ajax.php',
data:{
action: 'select_option'
//count: count;
},
dataType: 'html',
success: function(data){
jQuery('.content').html(data)
},
error: function(){
alert(fail)
}
})
});
I am developing a website using WP CMS where I want to implement post title as drop-down list as well as when users select a drop-down title the content show below within reload. I am here. What will I do if I want to retrieve content by id?
function select_options(){ ?>
<form action="" method="POST">
<select name="count" id="selectId" >
<?php
$posts = new WP_Query(array('posts_per_page' => 3, 'post_type' => 'post'));
while($posts->have_posts()) : $posts->the_post(); ?>
<option id="selection" value="<?php echo get_the_ID(); ?>"><?php echo get_the_title(); ?></option>
<?php endwhile;
die()
?>
</select>
</form>
<?php
}
add_action('wp_ajax_select_option', 'select_options');
add_action('wp_ajax_nopriv_select_option', 'select_options');
Javascript:
jQuery(document).ready(function(){
jQuery.ajax({
//var count = $('#selection').val();
type: 'POST',
url: 'wp-admin/admin-ajax.php',
data:{
action: 'select_option'
//count: count;
},
dataType: 'html',
success: function(data){
jQuery('.content').html(data)
},
error: function(){
alert(fail)
}
})
});
Share
Improve this question
edited Mar 26, 2017 at 18:47
MahdiY
4693 silver badges16 bronze badges
asked Mar 26, 2017 at 12:04
Wordpress StudentWordpress Student
117 bronze badges
1 Answer
Reset to default 1It's better to use the wp_ajax_ action in an init action.
In fact, wp_ajax_ action need to be accessable from anywhere. Use of the init action hook could make it work like it does.
Hope it works