实现视频弹出和无限加载效果需要使用以下 JavaScript 库:
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代码添加到展示页面
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」这个文章自定义字段中设置的视频链接。
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 的核心代码,因此不会对它们的升级造成影响,并且兼容性也非常好。