WP子比主题: functions.php文件功能拓展

WP子比主题: functions.php文件功能拓展

本代码用于WordPress子比主题的functions.php文件,以便拓展以下功能:

  1. 自动超链接网址:发布网址自动超链接,不必自己加超链接;
  2. 优化数据库的慢查询,解决数据库运行缓慢的问题
//自动超链接网址
add_filter('the_content', 'make_clickable');

//优化数据库慢查询
if ( ! function_exists( 'banzhuti_set_no_found_rows' ) ) :
 
    /**
     * 设置WP_Query的 'no_found_rows' 属性为true,禁用SQL_CALC_FOUND_ROWS
     * 更多优化教程-搬主题www.banzhuti.com
     * @param  WP_Query $wp_query The WP_Query instance. 
     * @return void
     */
    function banzhuti_set_no_found_rows( \WP_Query $wp_query ) {
        $wp_query->set( 'no_found_rows', true );
    }
endif;
add_filter( 'pre_get_posts', 'banzhuti_set_no_found_rows', 10, 1 );
 
if ( ! function_exists( 'banzhuti_set_found_posts' ) ) :
 
    /**
     * Workout the pagination values.
     *
     * 为这个wp_query构建和设置分页结果
     *
     */
    function banzhuti_set_found_posts( $clauses, \WP_Query $wp_query ) {
 
        // Don't proceed if it's a singular page.
        if ( $wp_query->is_singular()  ) {
            return $clauses;
        }
 
        global $wpdb;
 
        $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
        $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
        $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
 
        // 构建并运行查询。将结果设为'found_posts'
        // 在我们要运行的主要查询上设置参数.
        $wp_query->found_posts = $wpdb->get_var( "SELECT $distinct COUNT(*) FROM {$wpdb->posts} $join WHERE 1=1 $where" );
 
        // 计算出每页应该有多少文章
        $posts_per_page = ( ! empty( $wp_query->query_vars['posts_per_page'] ) ? absint( $wp_query->query_vars['posts_per_page'] ) : absint( get_option( 'posts_per_page' ) ) );
 
        // 设置max_num_pages(最大页数).
        $wp_query->max_num_pages = ceil( $wp_query->found_posts / $posts_per_page );
 
        // Return the $clauses so the main query can run.
        return $clauses;
    }
endif;
add_filter( 'posts_clauses', 'banzhuti_set_found_posts', 10, 2 );

/*用于小黑屋展示*/
if (file_exists(get_theme_file_path('/xy_block.php'))) {
    require_once get_theme_file_path('/xy_block.php');
}

以上内容由于在每次子比主题更新后会被重置,建议大家收藏本文,我会一直更新最新功能,以优化WP网站的最高效运营。

© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容