WordPress给搜索页面添加loading动画

WARNING: This article may be obsolete
This post was published in 2021-01-09. Obviously, expired content is less useful to users if it has already pasted its expiration date.

页面缓存插件并不能拯救Wordpress站内搜索的速度。

首先通过任意一款Code Snippets相关的插件,添加一段代码:

<?php

add_action( 'wp_enqueue_scripts', 'search_loading_script' );
function search_loading_script() {
    wp_enqueue_script(
        'search-loading-script', 
        'https://YOUR-PATH-TO-CUSTOM-JS', 
        array('jquery') 
    );
}


add_action('wp_head', function () { ?>
    <style>
        .search-loading-gif {
            display: none;
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            min-height: 50vh;
            max-height: 90vh;
            background-color: #fff;
            opacity: 1;
        }
    </style>
<?php });

add_action('wp_footer', function () {
    echo '
	<div class="search-loading-overlay">
	<img src="https://YOUR-PATH-TO-CUSTOM-SVG" 
	class="search-loading-gif" />
	</div>
	';
});

然后修改代码的第5,32行,把路径改为自定义路径,对应custom JS和custom SVG / gif。

Custom JS:

jQuery(document).ready(function ($) {
    $('.search-form').submit(function () {
        loading_svg_overlay();
        return true;
    });
    $('.page-numbers').click(function () {
        if (window.location.pathname.substring(0, 8) == '/search/') {
            loading_svg_overlay();
            return true;
        }
    });

    function loading_svg_overlay() {
        $('.search-loading-gif').css({
            'display': 'inline'
        });
        $('.search-loading-overlay').css({
            'position': 'fixed',
            'top': '0',
            'bottom': '0',
            'left': '0',
            'right': '0',
            'background-color': '#fff',
            'opacity': '0.8',
            'display': 'block',
            'z-index': '1001',
        });
    }
});

(注意第7行的URL判断要对应当前wordpress搜索链接的模版)

Custom SVG可以自定义。


 Last Modified in 2022-03-05 

Leave a Comment Anonymous comment is allowed / 允许匿名评论