doctorrm 2019-06-24 21:43:02 589 0
本次WordPress采用的主题为onepress
。
functions.php主题文件存在于wp-content/themes/onepress/functions
目录下,该文件提供了非常多的功能性函数,自己也可以写函数进一步扩展,很多其它文件都调用了functions.php文件中的函数。
我将functions.php的源码贴出来,里面有一些我阅读后的注释和分析。注意,不同主题中的函数可能会有所差别,前面的部分函数代码是我自己拓展的。
<?php
/**
* OnePress functions and definitions.
*
* @link https://developer.wordpress.org/themes/basics/theme-functions/
*
*
* @package OnePress
*/
//wordpress首页排除某些指定分类文章的显示
function exclude_category_home( $query ) {
if ( $query->is_home ) {//是否首页
$query->set( 'cat', "-15" ); //排除的指定分类id:15
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );
// 文章页添加展开收缩效果
function xcollapse($atts, $content = null){
extract(shortcode_atts(array("title"=>""),$atts));
return '<div style="margin: 0.5em 0;">
<div class="xControl">
<span class="xTitle">'.$title.'</span><i class="fa fa-plus-square" aria-hidden="true"></i><a href="javascript:void(0)" class="collapseButton xButton">展开/折叠</a>
<div style="clear: both;"></div>
</div>
<div class="xContent" style="display: none;">'.$content.'</div>
</div>';
}
add_shortcode('collapse', 'xcollapse');
// 文章页添加展开收缩效果结束
//评论者链接添加go跳转
function add_redirect_comment_link($text = ''){
$text=str_replace('href="', 'href="'.get_option('home').'/go/?url=', $text);
return $text;
}
add_filter('get_comment_author_link', 'add_redirect_comment_link', 5);
add_filter('comment_text', 'add_redirect_comment_link', 99);
//评论者链接添加go跳转结束
//文章内外链添加go跳转
function the_content_nofollow($content){
preg_match_all('/<a(.*?)href="(.*?)"(.*?)>/',$content,$matches);
if($matches){
foreach($matches[2] as $val){
if(strpos($val,'://')!==false && strpos($val,home_url())===false && !preg_match('/\.(jpg|jepg|png|ico|bmp|gif|tiff)/i',$val)){
$content=str_replace("href=\"$val\"", "href=\"".home_url()."/go/?url=$val\" ",$content);
}
}
}
return $content;
}
add_filter('the_content','the_content_nofollow',999);
//文章内外链添加go跳转结束
// 添加随便看看
function random_postlite() {
global $wpdb;
$query = "SELECT DISTINCT ID FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS tr ON (p.ID = tr.object_id ) INNER JOIN $wpdb->term_taxonomy AS tt ON(tr.term_taxonomy_id = tt.term_taxonomy_id AND taxonomy = 'category' AND tt.term_taxonomy_id in (16,17,18,19,20,22,23,134,162,164,166,168,174)) WHERE post_type = 'post' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
$random_id = $wpdb->get_var( $query );
wp_redirect( get_permalink( $random_id ) );
exit;
}
if ( isset( $_GET['random'] ) )
add_action( 'template_redirect', 'random_postlite' );
// 随便看看结束
if ( ! function_exists( 'onepress_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which
* runs before the init hook. The init hook is too late for some features, such
* as indicating support for post thumbnails.
*/
function onepress_setup() {
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
* If you're building a theme based on OnePress, use a find and replace
* to change 'onepress' to the name of your theme in all the template files.
* 让主题支持翻译
* 模板目录:/wp-content/themes/OnePress
*
*/
load_theme_textdomain( 'onepress', get_template_directory() . '/languages' );
/*
* Add default posts and comments RSS feed links to head.
* 支持主题在头部添加RSS信息流链接
*/
add_theme_support( 'automatic-feed-links' );
/*
* Let WordPress manage the document title.
* By adding theme support, we declare that this theme does not use a
* hard-coded <title> tag in the document head, and expect WordPress to
* provide it for us.
* 使得html文档不需要显式添加<title>标签,而是让WP帮我们添加
*/
add_theme_support( 'title-tag' );
/**
* Excerpt for page
* 支持文章摘要
*/
add_post_type_support( 'page', 'excerpt' );
/*
* Enable support for Post Thumbnails on posts and pages.
* 支持文章缩略图和页面缩略图,add_image_size(xxx)指定缩略图的大小
*
* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
*/
add_theme_support( 'post-thumbnails' );
add_image_size( 'onepress-blog-small', 300, 150, true );
add_image_size( 'onepress-small', 480, 300, true );
add_image_size( 'onepress-medium', 640, 400, true );
/*
* This theme uses wp_nav_menu() in one location.
* 注册导航菜单
*/
register_nav_menus(
array(
'primary' => esc_html__( 'Primary Menu', 'onepress' ),
)
);
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
* 将搜索框、评论框、画廊等装饰的最终生成代码为H5格式
*/
add_theme_support(
'html5',
array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
)
);
/*
* WooCommerce support.
* WooCommerce是WordPress的开源电子商务插件,它允许网站所有者只需几个步骤就可以快速在现有WordPress网站上集成一个功能齐全的在线商店
*/
add_theme_support( 'woocommerce' );
/**
* Add theme Support custom logo
* 支持自定义logo
* @since WP 4.5
* @sin 1.2.1
*/
add_theme_support(
'custom-logo',
array(
'height' => 36,
'width' => 160,
'flex-height' => true,
'flex-width' => true,
// 'header-text' => array( 'site-title', 'site-description' ), //
)
);
// Recommend plugins.
// 推荐的插件,包括插件名和插件对应的文件位置
add_theme_support(
'recommend-plugins',
array(
'wpforms-lite' => array(
'name' => esc_html__( 'Contact Form by WPForms', 'onepress' ),
'active_filename' => 'wpforms-lite/wpforms.php',
),
'famethemes-demo-importer' => array(
'name' => esc_html__( 'Famethemes Demo Importer', 'onepress' ),
'active_filename' => 'famethemes-demo-importer/famethemes-demo-importer.php',
),
)
);
// Add theme support for selective refresh for widgets.
// 支持选择性刷新小组件
add_theme_support( 'customize-selective-refresh-widgets' );
// Add support for WooCommerce.
add_theme_support( 'wc-product-gallery-zoom' );
add_theme_support( 'wc-product-gallery-lightbox' );
add_theme_support( 'wc-product-gallery-slider' );
/**
* Add support for Gutenberg.
*
* @link https://wordpress.org/gutenberg/handbook/reference/theme-support/
*/
add_theme_support( 'editor-styles' );
add_theme_support( 'align-wide' );
/*
* This theme styles the visual editor to resemble the theme style.
*/
add_editor_style( array( 'editor-style.css', onepress_fonts_url() ) );
}
endif;
add_action( 'after_setup_theme', 'onepress_setup' );//函数被钩入到after_setup_theme钩子上,after_setup_theme钩子比init钩子先运行。钩子的含义有点像别名。
/**
* Set the content width in pixels, based on the theme's design and stylesheet.
*
* Priority 0 to make it available to lower priority callbacks.
* 设置主题内容宽度。本函数优先级最低,为了能降级为低像素
* @global int $content_width
*/
function onepress_content_width() {
/**
* Support dynamic content width
* 支持动态内容宽度
*
* @since 2.1.1
*/
$width = absint( get_theme_mod( 'single_layout_content_width' ) );
if ( $width <= 0 ) {
$width = 800;
}
$GLOBALS['content_width'] = apply_filters( 'onepress_content_width', $width );
}
add_action( 'after_setup_theme', 'onepress_content_width', 0 );
/**
* Register widget area.
*
* 初始化组件(侧边栏)
* @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
*/
function onepress_widgets_init() {
register_sidebar(
array(
'name' => esc_html__( 'Sidebar', 'onepress' ),
'id' => 'sidebar-1',
'description' => '',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
)
);
if ( class_exists( 'WooCommerce' ) ) {
register_sidebar(
array(
'name' => esc_html__( 'WooCommerce Sidebar', 'onepress' ),
'id' => 'sidebar-shop',
'description' => '',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
)
);
}
for ( $i = 1; $i <= 4; $i++ ) {
register_sidebar(
array(
'name' => sprintf( __( 'Footer %s', 'onepress' ), $i ),
'id' => 'footer-' . $i,
'description' => '',
'before_widget' => '<aside id="%1$s" class="footer-widget widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
)
);
}
}
add_action( 'widgets_init', 'onepress_widgets_init' );
/**
* Enqueue scripts and styles.
* 将主题的assets中的脚本和样式推入队列
*/
function onepress_scripts() {
$theme = wp_get_theme( 'onepress' );
$version = $theme->get( 'Version' );
//如果不禁止谷歌字体,就采用
if ( ! get_theme_mod( 'onepress_disable_g_font' ) ) {
wp_enqueue_style( 'onepress-fonts', onepress_fonts_url(), array(), $version );
}
wp_enqueue_style( 'onepress-animate', get_template_directory_uri() . '/assets/css/animate.min.css', array(), $version );
wp_enqueue_style( 'onepress-fa', get_template_directory_uri() . '/assets/css/font-awesome.min.css', array(), '4.7.0' );
wp_enqueue_style( 'onepress-bootstrap', get_template_directory_uri() . '/assets/css/bootstrap.min.css', false, $version );
wp_enqueue_style( 'onepress-style', get_template_directory_uri() . '/style.css' );
$custom_css = onepress_custom_inline_style();
wp_add_inline_style( 'onepress-style', $custom_css );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'onepress-js-plugins', get_template_directory_uri() . '/assets/js/plugins.js', array( 'jquery' ), $version, true );
wp_enqueue_script( 'onepress-js-bootstrap', get_template_directory_uri() . '/assets/js/bootstrap.min.js', array(), $version, true );
// Animation from settings.
// 将动画设置赋值给变量,相当于提取出动画设置
$onepress_js_settings = array(
'onepress_disable_animation' => get_theme_mod( 'onepress_animation_disable' ),
'onepress_disable_sticky_header' => get_theme_mod( 'onepress_sticky_header_disable' ),
'onepress_vertical_align_menu' => get_theme_mod( 'onepress_vertical_align_menu' ),
'hero_animation' => get_theme_mod( 'onepress_hero_option_animation', 'flipInX' ),
'hero_speed' => intval( get_theme_mod( 'onepress_hero_option_speed', 5000 ) ),
'hero_fade' => intval( get_theme_mod( 'onepress_hero_slider_fade', 750 ) ),
'hero_duration' => intval( get_theme_mod( 'onepress_hero_slider_duration', 5000 ) ),
'hero_disable_preload' => get_theme_mod( 'onepress_hero_disable_preload', false ) ? true : false,
'is_home' => '',
'gallery_enable' => '',
'is_rtl' => is_rtl(),
);
// Load gallery scripts.
// 画廊配置的提取
$galley_disable = get_theme_mod( 'onepress_gallery_disable' ) == 1 ? true : false;
$is_shop = false;
//是否支持在线商店
if ( function_exists( 'is_woocommerce' ) ) {
if ( is_woocommerce() ) {
$is_shop = true;
}
}
// Don't load scripts for woocommerce because it don't need.
// 如果不支持在线商务,则不要加载对应脚本
if ( ! $is_shop ) {
if ( ! $galley_disable || is_customize_preview() ) {
$onepress_js_settings['gallery_enable'] = 1;
$display = get_theme_mod( 'onepress_gallery_display', 'grid' );
// 如果不需要自定义预览,则根据配置参数自行加载某一脚本即可。预览分为四种:masonry,justified,slider,carousel.
if ( ! is_customize_preview() ) {
switch ( $display ) {
case 'masonry':
wp_enqueue_script( 'onepress-gallery-masonry', get_template_directory_uri() . '/assets/js/isotope.pkgd.min.js', array(), $version, true );
break;
case 'justified':
wp_enqueue_script( 'onepress-gallery-justified', get_template_directory_uri() . '/assets/js/jquery.justifiedGallery.min.js', array(), $version, true );
break;
case 'slider':
case 'carousel':
wp_enqueue_script( 'onepress-gallery-carousel', get_template_directory_uri() . '/assets/js/owl.carousel.min.js', array(), $version, true );
break;
default:
break;
}
} else {
wp_enqueue_script( 'onepress-gallery-masonry', get_template_directory_uri() . '/assets/js/isotope.pkgd.min.js', array(), $version, true );
wp_enqueue_script( 'onepress-gallery-justified', get_template_directory_uri() . '/assets/js/jquery.justifiedGallery.min.js', array(), $version, true );
wp_enqueue_script( 'onepress-gallery-carousel', get_template_directory_uri() . '/assets/js/owl.carousel.min.js', array(), $version, true );
}
}
wp_enqueue_style( 'onepress-gallery-lightgallery', get_template_directory_uri() . '/assets/css/lightgallery.css' );
}
wp_enqueue_script( 'onepress-theme', get_template_directory_uri() . '/assets/js/theme.js', array(), $version, true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
if ( is_front_page() && is_page_template( 'template-frontpage.php' ) ) {
if ( get_theme_mod( 'onepress_header_scroll_logo' ) ) {
$onepress_js_settings['is_home'] = 1;
}
}
wp_localize_script( 'jquery', 'onepress_js_settings', $onepress_js_settings );
}
add_action( 'wp_enqueue_scripts', 'onepress_scripts' );
if ( ! function_exists( 'onepress_fonts_url' ) ) :
/**
* Register default Google fonts
* 如果没有指定某一特定字体的url,则设置默认字体为谷歌字体(open sans或raleway)并返回。
*/
function onepress_fonts_url() {
$fonts_url = '';
/*
* Translators: If there are characters in your language that are not
* supported by Open Sans, translate this to 'off'. Do not translate
* into your own language.
* 如果目标语言中存在某些字符不被Open Sans字体所支持,将Open Sans为关闭(off)状态
*/
$open_sans = _x( 'on', 'Open Sans font: on or off', 'onepress' );
/*
* Translators: If there are characters in your language that are not
* supported by Raleway, translate this to 'off'. Do not translate
* into your own language.
* 如果目标语言中存在某些字符不被raleway字体所支持,将raleway为关闭(off)状态
*/
$raleway = _x( 'on', 'Raleway font: on or off', 'onepress' );
// 如果raleway字体(优先)或open sans字体有一个被支持
if ( 'off' !== $raleway || 'off' !== $open_sans ) {
$font_families = array();
if ( 'off' !== $raleway ) {
$font_families[] = 'Raleway:400,500,600,700,300,100,800,900';
}
if ( 'off' !== $open_sans ) {
$font_families[] = 'Open Sans:400,300,300italic,400italic,600,600italic,700,700italic';
}
$query_args = array(
'family' => urlencode( implode( '|', $font_families ) ),
'subset' => urlencode( 'latin,latin-ext' ),
);
//将查询参数(family+subset)添加到谷歌字体url后面
$fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' );
}
return esc_url_raw( $fonts_url );
}
endif;
/**
* Glabel OnePress loop properties
* 定义全局循环属性数组
*
* @since 2.1.0
*/
global $onepress_loop_props;
$onepress_loop_props = array();
/**
* Set onepress loop property.
* 设置循环属性值
* @since 2.1.0
*
* @param string $prop
* @param string $value
*/
function onepress_loop_set_prop( $prop, $value ) {
global $onepress_loop_props;
$onepress_loop_props[ $prop ] = $value;
}
/**
* Get onepress loop property
* 获取设置循环属性值
* @since 2.1.0
*
* @param $prop
* @param bool $default
*
* @return bool|mixed
*/
function onepress_loop_get_prop( $prop, $default = false ) {
global $onepress_loop_props;
if ( isset( $onepress_loop_props[ $prop ] ) ) {
return apply_filters( 'onepress_loop_get_prop', $onepress_loop_props[ $prop ], $prop );
}
return apply_filters( 'onepress_loop_get_prop', $default, $prop );
}
/**
* Remove onepress loop property
* 移除获取设置循环属性
* @since 2.1.0
*
* @param $prop
*/
function onepress_loop_remove_prop( $prop ) {
global $onepress_loop_props;
if ( isset( $onepress_loop_props[ $prop ] ) ) {
unset( $onepress_loop_props[ $prop ] );
}
}
/**
* Trim the excerpt with custom length
* 将摘要裁剪为某一特定长度
* @since 2.1.0
*
* @see wp_trim_excerpt
* @param $text
* @param null $excerpt_length
* @return string
*/
function onepress_trim_excerpt( $text, $excerpt_length = null ) {
$text = strip_shortcodes( $text );
/** This filter is documented in wp-includes/post-template.php */
$text = apply_filters( 'the_content', $text );
$text = str_replace( ']]>', ']]>', $text );//将摘要中的>替换为>
// 将摘要长度裁剪为55
if ( ! $excerpt_length ) {
/**
* Filters the number of words in an excerpt.
*
* @since 2.7.0
*
* @param int $number The number of words. Default 55.
*/
$excerpt_length = apply_filters( 'excerpt_length', 55 );
}
/**
* Filters the string in the "more" link displayed after a trimmed excerpt.
*
* @since 2.9.0
*
* @param string $more_string The string shown within the more link.
*/
$excerpt_more = apply_filters( 'excerpt_more', ' ' . '…' );
return wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
/**
* Display the excerpt
* 展示摘要
* @param string $type
* @param bool $length
*/
function onepress_the_excerpt( $type = false, $length = false ) {
$type = onepress_loop_get_prop( 'excerpt_type', 'excerpt' );
$length = onepress_loop_get_prop( 'excerpt_length', false );
//根据摘要类型(摘要、标签、内容)分别显示
switch ( $type ) {
case 'excerpt':
the_excerpt();
break;
case 'more_tag':
the_content( '', true );
break;
case 'content':
the_content( '', false );
break;
default:
$text = '';
global $post;
//如果有摘要内容就显示,否则就取文章的开头内容
if ( $post ) {
if ( $post->post_excerpt ) {
$text = $post->post_excerpt;
} else {
$text = $post->post_content;
}
}
$excerpt = onepress_trim_excerpt( $text, $length );
if ( $excerpt ) {
// WPCS: XSS OK.
echo apply_filters( 'the_excerpt', $excerpt );
} else {
the_excerpt();
}
}
}
/************************将themes/onepress/inc/中的文件导入*****************************/
/**
* Config class
* 导入配置类
*
* @since 2.1.1
*/
require get_template_directory() . '/inc/class-config.php';
/**
* Load Sanitize
*/
require get_template_directory() . '/inc/sanitize.php';
/**
* Custom Metabox for this theme.
*/
require get_template_directory() . '/inc/metabox.php';
/**
* Custom template tags for this theme.
* 自定义主题的模板标签
*/
require get_template_directory() . '/inc/template-tags.php';
/**
* Custom functions that act independently of the theme templates.
* 自定义独立于主题模板的函数
*/
require get_template_directory() . '/inc/extras.php';
/**
* Dots Navigation class
*
* @since 2.1.0
*/
require get_template_directory() . '/inc/class-sections-navigation.php';
/**
* Customizer additions.
*/
require get_template_directory() . '/inc/customizer.php';
/**
* Add theme info page
* 添加主题信息页
*/
require get_template_directory() . '/inc/admin/dashboard.php';
/**
* Editor Style
* 编辑器样式
*
* @since 2.2.1
*/
require get_template_directory() . '/inc/admin/class-editor.php';
去打赏