Magnific Popup for Wordpress post body images

2019-09-05 22:26发布

问题:

I am working on a WordPress theme and I was wondering if there is a way of opening images in Magnific Popup which are inserted on a post body by the editor. So, any image I insert in a post through TinyMCE editor will open on Magnific Popup when clicked on the front end.

回答1:

There are a few different approaches to this question. I've outlined a couple below.

Option 1

Filter the content and apply a HTML attribute that can be targeted with Magnific Popup.

We can take a cue from this article and leverage the_content hook.

The "the_content" filter is used to filter the content of the post after it is retrieved from the database and before it is printed to the screen.

functions.php

Add the following to functions.php.

function prefix_content_gallery( $content ) {
    global $post;

    $pattern     = "/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
    $replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title="'.$post->post_title.'"$6>';
    $content     = preg_replace( $pattern, $replacement, $content );

    return $content;
}
add_filter( 'the_content', 'prefix_content_gallery' );

JS

$('.entry-content').magnificPopup({
    type: 'image',
    delegate: '[rel="lightbox"]',
    gallery: {
        enabled: true
    }
});

View Example


Option 2

Another option would be to selectively assign a CSS class to links which should be part of the image gallery.

  1. Add media to post and set "Link To" to "Media File" under Attachment Display Settings.

  1. Edit the image after it has been inserted into the post.

  1. Add a CSS class to the link which wraps the image.

JS

$('.entry-content').magnificPopup({
    type: 'image',
    delegate: '.entry-gallery',
    gallery: {
        enabled: true
    }
});

View Example