Magnific Popup for Wordpress post body images

霸气de小男生 提交于 2019-12-12 04:04:44

问题


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



来源:https://stackoverflow.com/questions/35293573/magnific-popup-for-wordpress-post-body-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!