i'm using Wordpress as content management system and my template has a div with box
class, and contains a dropdown list . my goal is getting the value of this droplist and query post in ajax method with this value,then reload just box
div using ajax , for getting more clear here is markup :
<select>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
</select>
------------------
<div class="content">
<?php
$args = array(
"meta_query" => array(
array(
'key' => 'meta',
'value' => '$select_value',
)
)
);
query_posts( $args );
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; else: ?>
<p>sorry no post found with this value.</p>
<?php endif; ?>
i think sample code is clear , but i want to do this processes:
user select an item in dropdown list --> get select value --> put it in $select_value --> run query --> show the div box
without reloading entire page using ajax...
Can someone help me out writting this?
<select id="select-dropdown">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
</select>
For this to achieve you should have knowledge of Admin Ajax in wordpress.
Admin Ajax:
in your
header.php
<script type="text/javascript">
var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
in you custom js file
my-custom.js, enqueue the js file
jQuery(document).ready(function(){
jQuery(body).on('change','#select-dropdown', function(){
var selected_item = jQuery(this).val();
jQuery.ajax({
type: "POST",
url: "ajax_url",
data: {
action: 'load_posts',
selected_item: selected_item,
},
success: function(res){
console.log(res);
//append the result in frontend
jQuery('.box').html(res);
},
})
})
});
In your function.php
function _boom_load_posts(){
//get your results here as per selected option
if(!empty($_POST['selected_item'])){
$selected_item = $_POST['selected_item'];
$output = '';
//rest of the code as per selected_item, store result in $output
$args = array(
"meta_query" => array(
array(
'key' => 'meta',
'value' => '$select_value',
)
)
);
query_posts( $args );
if ( have_posts() ) : while ( have_posts() ) : the_post();
$output .= get_the_content();
endwhile; else:
$output .= "<p>sorry no post found with this value.</p>"
endif;
echo $output;//you result here
die(1);
}
}
add_action('wp_ajax_load_posts', '_dot1_load_posts');
add_action('wp_ajax_no_priv_load_posts', '_dot1_load_posts');
make the required changes, as I can't post the whole code for you, make some efforts and the above code will help you get an idea that how it's going to work.