
给 Elementor 文章列表模块添加视频弹出和无限加载效果
视频弹出和瀑无限加载效果是 Elementor 高级版中包含的页面效果,但是只为这个效果就去购买高级版非常没有性价比。其实 Elementor 免费版也是可以实现这个效果的,而且并不需要太多代码。
实现视频弹出和无限加载效果所需的 JavaScript 库
视频弹出效果和无限加载效果肯定是通过 JavaScript 实现的,在本文所提到的案例中,我们使用的是 Magnific Popup 和 jQuery Infinite Ajax Scroll 这两个库,首先我们需要引入这两个库(这两个库我们已经在主题中注册过了,所以我们在这里省略了注册的代码)。
1 2 3 4 5 6 7 8 | add_action('wp_enqueue_scripts', function () { if (is_page(178)) { wp_enqueue_script('wprs-jquery-ias'); wp_enqueue_style('wprs-magnific-popup'); wp_enqueue_script('wprs-magnific-popup'); } }); |
因为我们只需要在某个页面中实现这两个效果,所以在添加代码的时候,我们需要做一个判断,只有当前页面是我们所需的页面时,才添加这两个 JS 库。
添加 Popup 和无限加载效果JS代码到所需的页面
因为我们已经在上面的代码中引入了所需的 JavaScript 库,我们直接把实现这两个效果的JS实例代码添加到对应页面的页脚即可。当然,如果你喜欢,也可以添加到网站的 JS 文件中统一管理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | add_action('wp_footer', function () { if ( ! is_page(178)) { return; } ?> <script> jQuery(document).ready(function($) { function activatePopup() { $('#feedback-videos .elementor-post__thumbnail__link').magnificPopup({ disableOn : 700, type : 'iframe', mainClass : 'mfp-fade', removalDelay: 160, preloader : false, fixedContentPos: false, }); } activatePopup(); var ias = jQuery.ias({ container : '.elementor-posts-container', item : 'article.elementor-post', pagination: 'nav.elementor-pagination', next : 'nav.elementor-pagination a.next', }); ias.extension(new IASSpinnerExtension()); ias.extension(new IASTriggerExtension({offset: 2})); ias.extension(new IASNoneLeftExtension({text: 'You reached the end'})); ias.extension(new IASPagingExtension({text: 'View More Videos'})); ias.extension(new IASHistoryExtension({prev: '#pagination a.prev'})); ias.on('rendered', function(items) { activatePopup(); }); }); </script> <?php }); |
有了上面的代码,页面列表无限加载的效果已经实现了,但是视频弹出还需要进一步处理才能实现。
修改文章链接为视频链接
Magnific Popup 弹出的视频是直接使用的链接中的视频地址,所以,我们需要修改列表中的文章链接为视频链接地址。我们可以通过 post_type_link
这个 Filter 来修改文章链接地址,下面的代码中,我们把 「feedback」文章类型的链接修改为 「_video_url」这个文章自定义字段中设置的视频链接。
1 2 3 4 5 6 7 8 9 10 11 12 | add_filter('post_type_link', function ($permalink, $post, $leavename) { if ($post->post_type === 'feedback') { $video_url = get_post_meta($post->ID, '_video_url', true); if ($video_url) { $permalink = $video_url; } } return $permalink; }, 999, 3); |
至此,在 Elementor 中实现视频弹出和无限加载的功能已经全部实现,主要使用了 wp_enqueue_scripts Action 来加载 JS 库,使用 wp_footer Action 来添加实例 JS 代码,使用了 post_type_link Filter来修改文章链接为视频链接,全程没有修改 WordPress 或 Elementor 的核心代码,所以不会影响WordPress或Elementor 升级,兼容性也不错。