0°

缓存wp_nav_menu,加快博客速度

1289 个字符,0 张图片,大约需要 2 分钟阅读

手动版,更方便 : 替换wp_nav_menu,加快博客速度

丢进function.php

//给 wp_nav_menu 加上对象缓存,加快效率
add_filter( 'pre_wp_nav_menu', 'wpjam_get_nav_menu_cache', 10, 2 );
function wpjam_get_nav_menu_cache( $nav_menu, $args ) {
    $cache_key      = wpjam_get_nav_menu_cache_key($args);
    $cached_menu    = get_transient( $cache_key );
    if ( ! empty( $cached_menu ) )
        return $cached_menu;

    return $nav_menu;
}

add_filter( 'wp_nav_menu', 'wpjam_set_nav_menu_cache', 10, 2 );
function wpjam_set_nav_menu_cache( $nav_menu, $args ) {
    $cache_key      = wpjam_get_nav_menu_cache_key($args);
    set_transient( $cache_key, $nav_menu, 86400 );
    
    return $nav_menu;
}

function wpjam_get_nav_menu_cache_key($args){
    $timestamp = get_transient('nav-menu-cache-timestamp');
    if($time === false){
        $timestamp = time();
        set_transient( 'nav-menu-cache-timestamp', $time, 86400 );
    }
    return apply_filters( 'nav_menu_cache_key' , 'nav-menu-' . md5( serialize( $args ).serialize(get_queried_object()) ) . $timestamp );
}

// 更新菜单,清理缓存
add_action( 'wp_update_nav_menu', 'wpjam_delete_nav_menu_cache' );
function wpjam_delete_nav_menu_cache( $menu_id, $menu_data){
    set_transient( 'nav-menu-cache-timestamp', time(), 86400 );
}

来自:http://blog.wpjam.com/m/cache-wp_nav_menu/

除非注明,否则均为喵喵喵博客原创文章,转载请以链接形式标明本文地址

本文链接:https://www.miaomiaomiao.org/562.html

0 条回复 A 作者 M 管理员
    当上帝赐给你荒野时,就意味着,他要你成为高飞的鹰
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论