milohuang / reverie

Reverie is a versatile HTML5 responsive WordPress framework based on ZURB's Foundation.
http://theakiba.com/reverie/
MIT License
916 stars 196 forks source link

Reveal Modal Pop-up using WordPress AJAX #204

Open tnog opened 11 years ago

tnog commented 11 years ago

This isn't a issue, but perhaps helpful to others. I created a plugin that integrates WordPress' native AJAX with Reveal so you can populate modal windows with WP content. Not only that, but you can use secondary links within open modal windows to page through previous/next post content. And also, the modal windows are centered in the page, even if they are resized to content of variable width. The jQuery code is below:

sketchbook_ajax.js


(function($) {

    $.fn.displayPost = function() {

        event.preventDefault();

        var post_id = $(this).data("id");
        var id = "#" + post_id;

        // Check if the reveal modal for the specific post id doesn't already exist by checking for it's length
        if($(id).length == 0 ) {
            // We'll add an ID to the new reveal modal; we'll use that same ID to check if it exists in the future.
            var modal = $('<div>').attr('id', post_id ).addClass('reveal-modal').appendTo('body');
            var ajaxURL = MyAjax.ajaxurl;
             $.ajax({
                type: 'POST',
                url: ajaxURL,
                data: {"action": "load-content", post_id: post_id },
                success: function(response) {
                    modal.empty().html(response).append('<a class="close-reveal-modal">&#215;</a>').foundation('reveal', 'open');
                    modal.bind('opened', function() {
                        // Reset visibility to hidden and set display: none on closed reveal-modal divs, for some reason not working by default when reveal close is triggered on .secondary links  
                        $(".reveal-modal:not('.reveal-modal.open')").css({'visibility': 'hidden', 'display' : 'none'})
                        // Trigger resize 
                        $(window).trigger('resize');
                    return false;
                    });
                }
            });
        }
         //If the div with the ID already exists just open it.
         else {
             $(id).foundation('reveal', 'open');
         }

         // Recalculate left margin on window resize to allow for absolute centering of variable width elements
         $(window).resize(function(){
             var left;
                left = Math.max($(window).width() - $(id).outerWidth(), 0) / 2;
                $(id).css({
                    left:left + $(window).scrollLeft()
                });
         });
    }

})(jQuery);

// Apply the function when we click on the .reveal link
jQuery(document).on("click", ".reveal,.secondary", function() {
    jQuery(this).displayPost();

});

// Close open modals via secondary paging links in open modal window
jQuery(document).on("click", ".secondary", function() {
    var id = jQuery(this).closest("div").attr("id");
        jQuery(id).foundation('reveal', 'close');
});

And here's the PHP code:


        public function __construct() {
             add_action( 'wp_enqueue_scripts', array($this, 'include_scripts' ));
            add_action( 'wp_ajax_load-content', array($this, 'load_ajax_content' ));
            add_action( 'wp_ajax_nopriv_load-content', array($this, 'load_ajax_content' ));

        }

/**
             * AJAX load image on Sketchbook page to mimic Tumblr
             */
           public function include_scripts() {

                if ( is_page('sketchbook-pages' ) ) {

                    // embed the javascript file to make the AJAX request
                    wp_enqueue_script( 'reveal', get_template_directory_uri() . '/js/foundation/foundation.reveal.js', array( 'jquery', 'reverie-js' ), '', true );
                    wp_enqueue_script( 'my-ajax-request', self::$url . 'js/sketchbook_ajax.js', array( 'jquery', 'reverie-js', 'reveal' ), '', true );
                    wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

                }
            }            

            private function paging_link_nav( $post_id ) {
                global $post;
                $post = get_post( $post_id );
                // Unfortunately, I'm relying on a 3rd party plugin to generate the paging links, http://www.ambrosite.com/plugins/next-previous-post-link-plus-for-wordpress
                return '<nav><ul><li class="prev"><a href="#" class="button radius previous-sketch secondary" data-id="'. previous_post_link_plus( array('loop' => 'true', 'return' => 'id') ) .'">Previous</a></li>
                <li class="next"><a href="#" class="button radius next-sketch secondary" data-id="'. next_post_link_plus( array('loop' => 'true', 'return' => 'id') ) .'">Next</a></li></ul></nav>'; 

            }

            /**
             * Function to call the content loaded for logged-in and anonymous users
            */
            public function load_ajax_content ( $post_id ) {

                $post_id = $_POST[ 'post_id' ];

                if (has_post_thumbnail($post_id)) {
                    $sketch_id = get_post_thumbnail_id($post_id);  
                    $attachment = get_post( $sketch_id );
                    $caption = $attachment->post_excerpt;
                    $response = '<figure>'. get_the_post_thumbnail($post_id, 'large-sketch') .'<figcaption><p>'. $caption .'</p></figcaption></figure>' . $this->paging_link_nav( $post_id );
                    echo $response;
                }

                die(1);
             }

Oh and also the corresponding template code. The important variable is the data-id populated with the post ID. Since sketchbook_ajax.js needs the post ID to assign a unique id to the reveal-modal windows.


 <ul id="sketchbook-container" class="large-block-grid-4">
            <?php 

            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
            $args = array(
              'post_type' => 'tn_cstm_sketchbook',
              'orderby' => 'menu_order',
              'order' =>  'ASC',
              'posts_per_page' => 8,
              'paged'=> $paged 
              );

              $loop = new WP_Query($args);
              while($loop->have_posts()) : $loop->the_post(); ?>

              <?php 

                if( has_post_thumbnail() ) :
                  $sketch = get_post_thumbnail_id($post->ID);     
                  $large_image = get_attachment_link( $sketch );
                   ?>git 

                  <li class="sketch-leaf">
                    <figure class="sketch-thumb">

                      <a href="<?php echo $large_image; ?>" data-id="<?php the_ID(); ?>"  class="reveal" >
                      <?php echo get_the_post_thumbnail($post->ID, 'medium-sketch'); ?>
                      </a> 
                      <figcaption>

                      </figcaption>

                      </figure>

                  </li>
                <?php endif; ?>

            <?php endwhile; ?>

          </ul>
randomfreeform commented 11 years ago

THANKS!!!!! (Not jammin with Reverie now but when I do in a week or so I'll give this a try.)

malfborger commented 11 years ago

Very good snippets, thanks @tnog

waqasy commented 10 years ago

Can you please guide me where to add the PHP code you mentioned above? In functions.php or page template?

tnog commented 10 years ago

I created a plugin and wrapped everything in a class, but you could probably modify the functions above and add them into your function.php file. You'll have to enqueue the .js file and add the template markup accordingly.

waqasy commented 10 years ago

Yes I also wrapped in class. Activated plugin with no errors, load all js and admin-ajax.php

But when I click on link nothing happens and the console shows me error "Uncaught ReferenceError: Foundation is not defined" on line 4 "Foundation.libs.reveal = {" and "Uncaught TypeError: Object [object Object] has no method 'foundation' sketchbook_ajax.js:3"

Is it possible to get your working version of plugin?

tnog commented 10 years ago

I just uploaded my plugin file into a new repository: https://github.com/tnog/sketchbook-plugin

Try downloading and playing around with it.

randomfreeform commented 10 years ago

VERY cool of you to offer this! I haven't tried it yet.. by chance is there a demo of it working in Reverie somewhere? Thx R

waqasy commented 10 years ago

tnog, Thank you so much :) I will checkt it

ameliapower commented 10 years ago

tnog, Thank you for this code. I have this working really nicely in my WP responsive theme. Just had to tweak it a little, .reveal instead of .foundation and a few adjustments here and there. Great stuff.