Update Loop with Form

I have a photo gallery I’m developing using WP as a means for content management. I’m relying heavily on some jQuery plugins to manage the UI styling and manipulation (via sorting). My problem is there are too many damn posts! 737, and each has a thumbnail which is displayed on the page. This inevitably bogs down any browser. Especially since the sorting plugin “clones” the images when it sorts them. The posts are built using a Wp_query script;

<?php
 $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
 $post_per_page = 15; // (-1 shows all posts) SETS NUMBER OF IMAGES TO DISPLAY!
 $do_not_show_stickies = 1; // 0 to show stickies
 $args=array(
'post_type' => array ('post'),
'orderby' => 'rand',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => $post_per_page
);
$pf_categorynotin = get_post_meta($wp_query->post->ID, true);
if($pf_categorynotin){
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => $pf_categorynotin,
            'operator' => 'NOT IN'
        )
    ); //category__in
}
$temp = $wp_query;  // assign orginal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query($args);

if( have_posts() ) :
    echo '<ul id="applications" class="applications pf_item3">';
    $r = 0;
    while ($wp_query->have_posts()) : $wp_query->the_post();
        $post_cat = array();
        $post_cat = wp_get_object_terms($post->ID, "category");
        $post_cats = array();
        $post_rel = "";
        for($h=0;$h<count($post_cat);$h++){
                $post_rel .= $post_cat[$h]->slug.' ';
                $post_cats[] = $post_cat[$h]->name;
            }
    $r++;
    echo'<li data-id="id-'. $r .'" data-type="'.$post_rel.'" >';
    if (get_post_meta($post->ID, 'port_thumb_image_url', true)) { ?>
<a  class="tozoom" href="<?php echo get_post_meta($post->ID, 'port_large_image_url', true); ?>" rel="example4" title="<?php echo $post->post_title; ?>">
<img src="<?php echo get_post_meta($post->ID, 'port_thumb_image_url', true); ?>" class="portfolio_box" alt="<?php the_title(); ?>" width="199px" height="134px" /></a>
    <?php } ?>
        </li>
    <?php endwhile ?>
         </ul>

and the items are sorted by their html5 tags with a menu in the sidebar.

Read More

You can see it working here; http://marbledesigns.net/marbledesigns/products

Right now it randomly loads 15 posts and displays them. I want to be able to reload posts based on my selection from the menu (via categories) and then update the list of images without refreshing the page. I want to be able to change not only which posts from which category are displayed, but also the posts per page as well.

I think AJAX is the way to do this, but I don’t want to undo a whole bunch of code in the menu in order to get it working. Right now the menu is styled radio buttons. Isn’t there a way I can take the same input from that form and update the parameters of the loop?

Looking for an efficient solution! Please help!

Related posts

Leave a Reply

1 comment

  1. Yes, AJAX is the way to go.

    Basically, you can write your own callback function for WP’s ajax hook in your theme’s functions.php file. And then your function can return data in any format you choose. I generally return JSON. I’ll walk you through setting it up.

    First, since it doesn’t appear that your visitors will be logging in, you will use the following hook with your callback function.

    add_action('wp_ajax_nopriv_get_images', 'get_images_callback');
    

    get_images is the $_POST action that you will be using for your form/jQuery ajax method.

    Next, you set up your ajax that will handle the request and returned the requested images. WordPress already has a script that handles AJAX. It is called admin-ajax.php, we post to it in the example below.

    jQuery(document).ready(function($) {
        var params = {
            action: 'get_images',
            category: 5,
            limit: 20
        };
        jQuery.post(<?php echo admin_url('admin-ajax.php'); ?>, params, function(response) {
            // do your magic!
        });
    });
    

    (Note: There is a better way of declaring the admin url than using a PHP echo statement, but I’m just giving you a quick and dirty example so that you can set this up on your own.)

    Finally, write the callback function that you added the action for. We will return JSON, but you can also just opt to return plain unencoded data.

    function get_images_callback(){
        $category = $_POST('category'); //get the requested category
        $limit = $_POST('limit'); //get the requested limit
    
        // your WP Query retrieves the appropriate posts/images and stores data to $images
        // you might also return the number of images in $num
        // and perhaps you'll return some other data in $data
    
        header('Content-type: application/json');
        print json_encode(array('images' => $images, 'number' => $num, 'data' => $data));
        die();
    }
    

    And there you have it. In your jQuery function, be sure to handle the returned data appropriately. To get the data, you’d just reference them like this: response.images, response.num, or response.data. If images is returned as an array, you’ll have to iterate over it to get to the data, as you would with any other array. ie.

    jQuery.each(response.images,function(key,val){
        // do stuff with the values
    }); 
    

    (Btw, even with only 15 images, that is one SLOW-loading page. Why not load the actual thumbnails and then call the larger image when the user selects it? …check your thumb sizes…)