自定义wordpress头部代码:实现keywords和description
wordprss默认没有keywords和description,要实现这个功能,可以自己重视头部代码,从而达到这个目的。
将下面的代码加入到Functions.php,并在主题对应的位置加上<?php mutheme_head(); ?>,即在<?php wp_head(); ?>加上就OK了。
//头部代码优化
function theme_head() { ?>
<?php if ( is_home() ) { ?><title><?php bloginfo( 'name' ); ?> - <?php bloginfo( 'description' ); ?></title><?php } ?>
<?php if ( is_search() ) { ?><title><?php _e( 'Search"');the_search_query();echo """; ?> - <?php bloginfo( 'name' ); ?></title><?php } ?>
<?php if ( is_single() ) { ?><title><?php echo trim( wp_title( '', 0 ) ); ?> - <?php bloginfo( 'name' ); ?></title><?php } ?>
<?php if ( is_author() ) { ?><title><?php wp_title( "" ); ?> - <?php bloginfo( 'name' ); ?></title><?php } ?>
<?php if ( is_archive() ) { ?><title><?php single_cat_title(); ?> - <?php bloginfo( 'name' ); ?></title><?php } ?>
<?php if ( is_year() ) { ?><title><?php the_time( 'Y' ); ?> - <?php bloginfo( 'name' ); ?></title><?php } ?>
<?php if ( is_month() ) { ?><title><?php the_time( 'F' ); ?> - <?php bloginfo( 'name' ); ?></title><?php } ?>
<?php if ( is_page() ) { ?><title><?php echo trim( wp_title( '', 0 ) ); ?> - <?php bloginfo( 'name' ); ?></title><?php } ?>
<?php if ( is_404() ) { ?><title>404 - <?php bloginfo( 'name' ); ?></title><?php } ?>
<?php
global $post;
if ( is_home() ) {
$keywords = 'Program Say,程序,代码,Linux';
$description = '记录一些常用的函数和瞎折腾的过程……';
} elseif ( is_single() ) {
$keywords = get_post_meta( $post->ID, "keywords", true );
if ( $keywords == "" ) {
$tags = wp_get_post_tags( $post->ID );
foreach ( $tags as $tag ) {
$keywords = $keywords . $tag->name . ",";
}
$keywords = rtrim( $keywords, ', ' );
}
$description = get_post_meta( $post->ID, "description", true );
if ( $description == "" ) {
if ( $post->post_excerpt ) {
$description = $post->post_excerpt;
} else {
$description = mb_strimwidth(strip_shortcodes(strip_tags(apply_filters('the_content', $post->post_content))), 0, 120,"...");
}
}
} elseif ( is_page() ) {
$keywords = get_post_meta( $post->ID, "keywords", true );
$description = get_post_meta( $post->ID, "description", true );
} elseif ( is_category() ) {
$keywords = single_cat_title( '', false );
$description = category_description();
} elseif ( is_tag() ) {
$keywords = single_tag_title( '', false );
$description = tag_description();
}elseif ( is_search() ) {
$skey = get_search_query();
$keywords = $skey;
$description = "您正在搜索:".$skey;
}
$keywords = trim( strip_tags( $keywords ) );
$description = str_replace(array("\r\n", "\r", "\n"), "", trim( strip_tags( $description ) ));
?>
<meta name="keywords" content="<?php echo $keywords; ?>" />
<meta name="description" content="<?php echo $description; ?>" />
<?php
}