Search code examples
phpjquerywordpressmagnific-popup

Magnific Popup with Wordpress Galleries


I am building a Wordpress theme and I want to add Magnific Popup - dimsemenov.com/plugins/magnific-popup/

I managed to get it working with single images with the following code in my functions.php file:

/**
* Add title back to images
*/
function pexeto_add_title_to_attachment( $markup, $id ){
    $att = get_post( $id );
    return str_replace('<a ', '<a title="'.$att->post_title.'" ', $markup);
}
add_filter('wp_get_attachment_link', 'pexeto_add_title_to_attachment', 10, 5);

add_action('wp_enqueue_scripts', 'enqueue_magnificpopup_styles');
function enqueue_magnificpopup_styles() {
    wp_register_style('magnific_popup_style', get_stylesheet_directory_uri().'/js/magnific-popup.css', array('style.css'));
    wp_enqueue_style('magnific_popup_style');
}

add_action('wp_enqueue_scripts', 'enqueue_magnificpopup_scripts');
function enqueue_magnificpopup_scripts() {
    wp_register_script('magnific_popup_script', get_stylesheet_directory_uri().'/js/jquery.magnific-popup.min.js', array('jquery'));
    wp_enqueue_script('magnific_popup_script');
    wp_register_script('magnific_init_script', get_stylesheet_directory_uri().'/js/jquery.magnific-popup-init.js', array('jquery'));
    wp_enqueue_script('magnific_init_script');
}

However it says 'Image could not be loaded' when I click an image in a Wordpress Gallery as it obviously has different HTML markup. Has anyone found a way to make this work with Wordpress Galleries? Thanks.


Solution

  • Something like this should work if the images are linked to "image file". Put this in a javascript file and enqueue the file after jQuery is ready.

    jQuery(document).ready(function($) {
            $(".gallery-icon a").magnificPopup();
        });