1

I have a created a list of categories in admin area using WPAlchemy, following is the code:

<?php 
$mb->the_field('s_cat'); 

$args = array(
'name'               => $mb->get_the_name(),
'id'                 => $mb->get_the_name(),
'selected'           => html_entity_decode($mb->get_the_value()),
'class'              => 'catlist',
'orderby'            => 'ID', 
'order'              => 'ASC',
'hide_empty'         => 0, 
'child_of'           => 0,
'hierarchical'       => 1, 
'depth'              => 2,
'hide_if_empty'      => false ); 

wp_dropdown_categories( $args ); 
?> 

Now i have created a function to create a list of posts, following is the code:

function fn_dropdown_post($cat_id) {
$args=array(
    'cat' => $cat_id,
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'caller_get_posts'=> 1
);

$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
?>
    <select name="menu">
    <?php
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <option value="<?php the_ID() ?>"><?php the_title(); ?></option>
    <?php
    endwhile;
    ?>
    </select>
<?php
}
wp_reset_query();
}

Works fine so far.

I want to display the list of posts when a category is selected , i tried following code which is not working:

<script>
jQuery(document).ready(function(e) {
    jQuery('.catlist').change(function() {
        <?php fn_dropdown_post(" ?> jQuery(this).val() <?php "); ?>;
    });
});
</script>

In the above code jQuery(this).val() is showing the value of selected category.

Any suggestions please?

1 Answer 1

0

I found this can be done using ajax

<script>
jQuery(document).ready(function() {
    jQuery('.catlist').change(function(){ 
        jQuery.ajax({
            type: 'POST',
            url: 'http://www.mywebsite.com/wp-admin/admin-ajax.php',
            data: {
                action: 'fn_dropdown_post',
                cat_id: jQuery('.catlist').val(),
            },
            success: function(data, textStatus, XMLHttpRequest){
                jQuery("#post-list").empty();
                jQuery("#post-list").append(data);
            },
            error: function(MLHttpRequest, textStatus, errorThrown){
                alert(errorThrown);
            }
        });
    });
});
</script>

However i am still trying to figure it out what's the proper way to use AJAX with wordpress. There are lots of tutorials, but non of them explains the topic in simple language.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.