给 Elementor 文章列表模块添加视频弹出和无限加载效果

视频弹出和瀑布流无限加载是 Elementor 高级版中提供的页面效果,但仅仅为了这个效果而购买高级版并不划算。实际上,Elementor 免费版也可以实现这两个效果,而且不需要太多代码。

实现视频弹出和无限加载效果需要使用以下 JavaScript 库:

视频弹出效果和无限加载效果肯定是通过 JavaScript 实现的。在本文提到的案例中,我们使用的是Magnific PopupjQuery Infinite Ajax Scroll 这两个库,首先,我们需要引入这两个库。由于这两个库已经在主题中注册,因此我们可以省略注册代码。

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 文件中以进行统一管理。

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 的核心代码,因此不会对它们的升级造成影响,并且兼容性也非常好。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注