我们喜欢WordPress,但并非所有人都愿意使用其所有默认设置和显示(尤其是帖子的显示方式)来解决。 我们被告知,独特性对网站的品牌影响很大,这给访问者留下了深刻的印象,多年来,博客和开发人员一直在努力调整帖子的显示方式,以使其尽可能独特。
今天,我们将专注于您可以执行的智能调整,以改善WordPress帖子显示。 无论您是要更改帖子显示以增强用户体验还是要增加收入或页面展示次数,都有一种无需插件即可实现的方法,并且此处列出的大多数摘要都易于实现,而在大多数情况下,您只需需要复制并粘贴提供的代码。
希望您会发现这些调整对您的项目有用,喜欢自定义!
前端
1.更改摘要长度
下面的调整将更改您的摘录长度,您只需将以下代码行添加到您的functions.php文件中,并将值75作为摘录长度。
add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($len) { return 75; }
[来源:Danny van Kooten]
2. Twitter风格的“时间前”日期
大多数人不知道WordPress具有内置的功能,可以使用“ Time Ago”格式显示日期,并且下面的代码段可以粘贴到循环中的任何位置,以使用格式显示日期。
Posted <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago';
[资料来源:PHP代码段]
3.在RSS供稿中显示帖子缩略图
在WordPress 2.9中引入的the_post_thumbnail()
函数对于添加和显示附加到帖子的缩略图非常有用。 坏消息是没有内置的方法可以在RSS feed中显示缩略图。 下面的功能将解决此问题。 只需将其粘贴到您的functions.php文件中,将其保存,帖子缩略图将自动显示在您的RSS feed中。
// show post thumbnails in feeds
function diw_post_thumbnail_feeds($content) { global $post; if(has_post_thumbnail($post->ID)) { $content = '<div>' . get_the_post_thumbnail($post->ID) . '</div>' . $content; } return $content;}add_filter('the_excerpt_rss', 'diw_post_thumbnail_feeds');add_filter('the_content_feed', 'diw_post_thumbnail_feeds');
[来源: 深入研究WordPress ]
4.将搜索限制为仅发布标题
您可以将此片段添加到WordPress主题的functions.php文件中,以将搜索限制为仅发布标题。
function __search_by_title_only( $search, &$wp_query )
{
if ( empty($search) )
return $search; // skip processing - no search term in query
$q =& $wp_query->query_vars;
// wp-includes/query.php line 2128 (version 3.1)
$n = !empty($q['exact']) ? '' : '%';
$searchand = '';
foreach( (array) $q['search_terms'] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
$searchand = ' AND ';
}
$term = esc_sql( like_escape( $q['s'] ) );
if ( empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s'] )
$search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
if ( !empty($search) ) {
$search = " AND ({$search}) ";
if ( !is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = '') ";
}
return $search;
}
add_filter( 'posts_search', '__search_by_title_only', 10, 2 );
[来源: WpSnipp ]
5.在每个帖子上显示一个递增的数字
下面的调整将使您在每个帖子上显示一个递增的数字,并且实现起来非常简单。 首先,将以下函数粘贴到functions.php文件中:
function updateNumbers() {
global $wpdb;
$querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
$counts = 0 ;
if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post);
$counts++;
add_post_meta($post->ID, 'incr_number', $counts, true);
update_post_meta($post->ID, 'incr_number', $counts);
endforeach;
endif;
}
add_action ( 'publish_post', 'updateNumbers' );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );
完成后,您可以使用以下代码显示帖子编号。 注意,它必须在循环中使用。
<?php echo get_post_meta($post->ID,'incr_number',true); ?>
6.从WordPress Feed中排除帖子
想要从Feed中排除某些帖子? 这是给您的调整。 请注意,您只应在要过滤的位置进行过滤; 在我们的示例中,它位于Feed $wp_query->is_feed
。 如果您不这样做,那么过滤器也将在您的后端运行,并且这些帖子将不会显示在帖子概述中。
该函数有两个参数。 为第一个参数$where
提供SQL字符串的扩展名,该扩展名将负责根据ID进行过滤。 然后,您需要在方括号内插入您要过滤的帖子ID 。
function fb_post_exclude($where, $wp_query = NULL) {
global $wpdb;
if ( !$wp_query )
global $wp_query;
if ($wp_query->is_feed) {
// exclude post with id 40 and 9
$where .= " AND $wpdb->posts.ID NOT IN (40, 9)";
}
return $where;
}
add_filter( 'posts_where','fb_post_exclude', 1, 2 );
[来源: WP工程师 ]
7.搜索查询返回单个结果时重定向到发布
将此片段放入WordPress主题的functions.php文件中,以在WordPress仅返回单个搜索结果时自动将搜索重定向到该帖子。
add_action('template_redirect', 'single_result');
function single_result() {
if (is_search()) {
global $wp_query;
if ($wp_query->post_count == 1) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
}
}
}
[来源: WpSnipp ]
8.从the_content自动创建元描述
将此片段添加到WordPress主题的functions.php文件中,将自动从WordPress帖子中创建一个元描述,并去除所有短代码和标签。 另外,请确保将其放在WordPress主题的header.php中 ,否则此代码段将不起作用。
function create_meta_desc() {
global $post;
if (!is_single()) { return; }
$meta = strip_tags($post->post_content);
$meta = strip_shortcodes($post->post_content);
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 125);
echo "<meta name='description' content='$meta' />";
}
add_action('wp_head', 'create_meta_desc');
[来源: WpSnipp ]
9.自动用会员链接替换单词
要自动用会员链接替换单词,只需将以下代码粘贴到您的functions.php文件中。 切记输入您的单词/链接,如下面的示例代码所示。
function replace_text_wps($text){
$replace = array(
// 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
'thesis' => '<a href="http://mysite.com/myafflink">thesis</a>',
'studiopress' => '<a href="http://mysite.com/myafflink">studiopress</a>'
);
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
[来源: catswhoblog.com ]
10.在the_excerpt的末尾添加“ Read More”永久链接
将下面的代码片段添加到WordPress主题的functions.php文件中,将在the_excerpt
的末尾添加一个“阅读更多”永久链接,就像the_content
所做的一样。
function excerpt_readmore($more) {
return '... <a href="'. get_permalink($post->ID) . '" class="readmore">' . 'Read More' . '</a>';
}
add_filter('excerpt_more', 'excerpt_readmore');
[来源: WpSnipp ]
11.显示没有插件的相关文章
安装以下代码将使您的WordPress网站根据当前帖子标签显示相关帖子。 您需要将其放置在single.php中 ,或者放置在任何想要显示相关文章的位置。
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'showposts'=>5, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<h3>Related Posts</h3><ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
}
?>
[来源:Bin-Co]
12.在侧边栏中创建自己的热门帖子
设置侧边栏小部件以显示受欢迎的帖子非常容易。 只需将下面的代码复制并粘贴到sidebar.php文件中。 如果您需要更改显示的帖子数量,可以将第3行末尾的5更改为您希望的任何数量。
<h2>Popular Posts</h2>
<ul>
<?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5");
foreach ($result as $post) {
setup_postdata($post);
$postid = $post->ID;
$title = $post->post_title;
$commentcount = $post->comment_count;
if ($commentcount != 0) { ?>
<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
<?php echo $title ?></a> {<?php echo $commentcount ?>}</li>
<?php } } ?>
</ul>
[来源: 专业博客设计 ]
13.设置过期日期/时间
下面是一个有用的代码,您可以将其放入WordPress主题中,以实现根据日期和时间创建过期的可能性。 编辑您的主题,并将当前的WordPress循环替换为此“被黑客入侵”的循环:
<?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
$expirationtime = get_post_custom_values('expiration');
if (is_array($expirationtime)) {
$expirestring = implode($expirationtime);
}
$secondsbetween = strtotime($expirestring)-time();
if ( $secondsbetween > 0 ) {
// For exemple... the_title();
the_excerpt();
}
endwhile;
endif;
?>
要创建具有日期/时间到期的帖子,您只需创建一个自定义字段即可。 将到期作为密钥,并将日期/时间(格式: mm / dd / yyyy 00:00:00 )作为值。 该特定时间戳记之后,该帖子将不会显示。
[来源: WpRecipes ]
14.列出将来的帖子
WordPress允许列出将来的帖子,并且要实现此功能,只需将代码粘贴到您希望将来显示的帖子的任何位置:
<div id="zukunft">
<div id="zukunft_header"><p>Future events</p></div>
<?php query_posts('showposts=10&post_status=future'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div>
<p><strong><?php the_title(); ?></strong><?php edit_post_link('e',' (',')'); ?><br />
<span class="datetime"><?php the_time('j. F Y'); ?></span></p>
</div>
<?php endwhile; else: ?><p>No future events scheduled.</p><?php endif; ?>
</div>
[来源: WpRecipes ]
15.仅向搜索引擎访问者显示AdSense
可以从搜索引擎的结果向访问者显示AdSense,这是实现此目的的代码,只需将下面的代码粘贴到主题的functions.php文件中即可。
function scratch99_fromasearchengine(){
$ref = $_SERVER['HTTP_REFERER'];
$SE = array('/search?', 'images.google.', 'web.info.com', 'search.', 'del.icio.us/search', 'soso.com', '/search/', '.yahoo.');
foreach ($SE as $source) {
if (strpos($ref,$source)!==false) return true;
}
return false;
}
$SE
数组是您指定搜索引擎的位置。 您可以通过向数组添加新元素来添加新的搜索引擎,然后只需将以下代码粘贴到模板中您希望展示AdSense广告的任何位置即可! 广告只会向搜索引擎结果的访问者展示。
if (function_exists('scratch99_fromasearchengine')) {
if (scratch99_fromasearchengine()) {
INSERT YOUR CODE HERE
}
}
后端
1.在编辑器中允许更多HTML标记
默认情况下,WordPress编辑器不允许与XHTML 1.0标准不兼容HTML标记。 但是,下面显示的代码将迫使编辑器接受更多标签。 您可以将其粘贴到主题的functions.php文件中,将其保存,该函数很好用。
function fb_change_mce_options($initArray) {
// Comma separated string od extendes tags
// Command separated string of extended elements
$ext = 'pre[id|name|class|style],iframe[align|longdesc|name|width|height|frameborder|scrolling|marginheight|marginwidth|src]';
if ( isset( $initArray['extended_valid_elements'] ) ) {
$initArray['extended_valid_elements'] .= ',' . $ext;
} else {
$initArray['extended_valid_elements'] = $ext;
}
// maybe; set tiny paramter verify_html
//$initArray['verify_html'] = false;
return $initArray;
}
add_filter('tiny_mce_before_init', 'fb_change_mce_options');
[来源: WP工程师 ]
2.设置默认编辑器
下面的代码段修改了WordPress管理员中的默认编辑器。 您可以使用Visual Editor ,也可以选择HTML Editor ,只需将其中之一添加到functions.php文件中。
# This sets the Visual Editor as default
add_filter( 'wp_default_editor', create_function('', 'return "tinymce";') );
# This sets the HTML Editor as default
add_filter( 'wp_default_editor', create_function('', 'return "html";') );
[来源: WP-Snippets ]
3.为不同的帖子类型设置不同的编辑器样式表
通过将以下代码粘贴到functions.php文件中,您可以为不同的帖子类型设置不同的编辑器样式表。 您将需要根据帖子类型对它进行调整,并记住还要更改样式表名称 。
function my_editor_style() {
global $current_screen;
switch ($current_screen->post_type) {
case 'post':
add_editor_style('editor-style-post.css');
break;
case 'page':
add_editor_style('editor-style-page.css');
break;
case 'portfolio':
add_editor_style('editor-style-portfolio.css');
break;
}
}
add_action( 'admin_head', 'my_editor_style' );
[来源:WPStorm]
4.允许上传更多文件类型
由于某些原因,WordPress Uploader不允许您上传某些文件类型,例如Textmate的.tmCommand 。 如果您需要将这些类型的文件上传到WordPress站点,则这里提供了一个功能片段,您可以执行此操作,而只需将其粘贴到functions.php文件中即可。 您还可以通过在第4行上添加它们来添加更多文件类型,并用竖线(|)分隔。
<?php
function addUploadMimes($mimes) {
$mimes = array_merge($mimes, array(
'tmbundle|tmCommand|tmDragCommand|tmSnippet|tmLanguage|tmPreferences' => 'application/octet-stream'
));
return $mimes;
}
?>
add_filter('upload_mimes', 'addUploadMimes');
[来源: pioupioum.fr ,通过WpRecipes ]
5.启用TinyMCE编辑器以发布the_excerpt
将以下代码片段放入WordPress主题的functions.php文件中,即可将TinyMCE编辑器添加到文章摘录的文本区域中。
function tinymce_excerpt_js(){ ?>
<script type="text/javascript">
jQuery(document).ready( tinymce_excerpt );
function tinymce_excerpt() {
jQuery("#excerpt").addClass("mceEditor");
tinyMCE.execCommand("mceAddControl", false, "excerpt");
}
</script>
<?php }
add_action( 'admin_head-post.php', 'tinymce_excerpt_js');
add_action( 'admin_head-post-new.php', 'tinymce_excerpt_js');
function tinymce_css(){ ?>
<style type='text/css'>
#postexcerpt .inside{margin:0;padding:0;background:#fff;}
#postexcerpt .inside p{padding:0px 0px 5px 10px;}
#postexcerpt #excerpteditorcontainer { border-style: solid; padding: 0; }
</style>
<?php }
add_action( 'admin_head-post.php', 'tinymce_css');
add_action( 'admin_head-post-new.php', 'tinymce_css');
[来源: WpSnipp ]
6.发布格式–主题的更多创新方式
下面的语法提供了一些可能的帖子格式,可以在文章中直接选择和使用它们,而您需要做的就是将代码放入主题的functions.php文件中。
add_theme_support( 'post-formats', array( 'aside', 'audio', 'image', 'video' ) );
[来源: WP工程师 ]
7.在“编辑帖子和页面概述”中也显示帖子缩略图
WordPress 2.9版引入了“发布缩略图”功能。 非常棒,要在“编辑帖子和页面概述”中也显示帖子缩略图,可以将以下代码放入插件或将其复制到主题的functions.php文件中。
if ( !function_exists('fb_AddThumbColumn') && function_exists('add_theme_support') ) {
// for post and page
add_theme_support('post-thumbnails', array( 'post', 'page' ) );
function fb_AddThumbColumn($cols) {
$cols['thumbnail'] = __('Thumbnail');
return $cols;
}
function fb_AddThumbValue($column_name, $post_id) {
$width = (int) 35;
$height = (int) 35;
if ( 'thumbnail' == $column_name ) {
// thumbnail of WP 2.9
$thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
// image from gallery
$attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
if ($thumbnail_id)
$thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
elseif ($attachments) {
foreach ( $attachments as $attachment_id => $attachment ) {
$thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
}
}
if ( isset($thumb) && $thumb ) { echo $thumb; }
else { echo __('None'); }
}
}
// for posts
add_filter( 'manage_posts_columns', 'fb_AddThumbColumn' );
add_action( 'manage_posts_custom_column', 'fb_AddThumbValue', 10, 2 );
// for pages
add_filter( 'manage_pages_columns', 'fb_AddThumbColumn' );
add_action( 'manage_pages_custom_column', 'fb_AddThumbValue', 10, 2 );
}
[来源: WP工程师 ]
8.在管理员中创建自定义帖子状态消息
此调整最初是由开发人员编写的,目的是使客户端针对作者创建的每个帖子显示自定义消息。 在这种情况下,帖子中的消息可能为拒绝 , 错误 , 源 , 最终等。您可以在代码的注释下方更改消息, 即自定义状态消息数组 ,以确保您也更改了类名。您可以在评论后更改它们,并更改下面消息的颜色 。
add_filter('display_post_states', 'custom_post_state');
function custom_post_state($states) {
global $post;
$show_custom_state = get_post_meta($post->ID, '_status');
if ($show_custom_state) {
$states[] = __('<span class="custom_state ' . strtolower($show_custom_state[0]) . '">' . $show_custom_state[0] . '</span>');
}
return $states;
}
add_action('post_submitbox_misc_actions', 'custom_status_metabox');
function custom_status_metabox() {
global $post;
$custom = get_post_custom($post->ID);
$status = $custom["_status"][0];
$i = 0;
/* ----------------------------------- */
/* Array of custom status messages */
/* ----------------------------------- */
$custom_status = array('Spelling', 'Review', 'Errors', 'Source', 'Rejected', 'Final', );
echo '<div class="misc-pub-section custom">';
echo '<label>Custom status: </label><select name="status">';
echo '<option class="default">Custom status</option>';
echo '<option>-----------------</option>';
for ($i = 0; $i < count($custom_status); $i++) {
if ($status == $custom_status[$i]) {
echo '<option value="' . $custom_status[$i] . '" selected="true">' . $custom_status[$i] . '</option>';
} else { echo '<option value="' . $custom_status[$i] . '">' . $custom_status[$i] . '</option>'; }
}
echo '</select>';
echo '<br /></div>';
}
add_action('save_post', 'save_status');
function save_status() {
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post->ID;
}
update_post_meta($post->ID, "_status", $_POST["status"]);
}
add_action('admin_head', 'status_css');
function status_css() {
echo '<style type="text/css">
.default{font-weight:bold;}
.custom{border-top:solid 1px #e5e5e5;}
.custom_state{
font-size:9px;
color:#666;
background:#e5e5e5;
padding:3px 6px 3px 6px;
-moz-border-radius:3px;
}
/* ----------------------------------- */
/* change color of messages below */
/* ----------------------------------- */
.spelling{background:#4BC8EB;color:#fff;}
.review{background:#CB4BEB;color:#fff;}
.errors{background:#FF0000;color:#fff;}
.source{background:#D7E01F;color:#333;}
.rejected{background:#000000;color:#fff;}
.final{background:#DE9414;color:#333;}
</style>';
}
[来源: WpSnipp ]
9.设置最大帖子标题长度
将此PHP代码添加到WordPress主题的functions.php文件中,将设置可以在您的帖子标题中显示的最大单词数,这非常方便!
function maxWord($title){
global $post;
$title = $post->post_title;
if (str_word_count($title) >= 10 ) //set this to the maximum number of words
wp_die( __('Error: your post title is over the maximum word count.') );
}
add_action('publish_post', 'maxWord');
[来源: WpSnipp ]
10.如何更改WordPress编辑器字体
讨厌WordPress编辑器中使用的当前字体? 可以将其更改为摩纳哥(Monaco)或Consolas等现代字体,只需将代码粘贴到WordPress主题的functions.php文件中即可。
function change_editor_font(){
echo "<style type='text/css'>
#editorcontainer textarea#content {
font-family: Monaco, Consolas, \"Andale Mono\", \"Dejavu Sans Mono\", monospace;
font-size:14px;
color:#333;
}
</style>";
}
add_action("admin_print_styles", "change_editor_font");
[来源:shailan.com,通过WpRecipes ]
11.在帖子/页面发布时自动添加自定义字段
一个代码片段,用于在发布自定义字段时自动将它们安装到页面或帖子中。 您可以将下面的代码添加到主题文件夹内的functions.php文件中。 当然,不要忘记更改自定义字段名称 。
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
add_post_meta($post_ID, 'field-name', 'custom value', true);
}
}
[来源:wpCanyon]
12.摆脱未使用的帖子修订
这是一个非常方便SQL查询,它将立即删除所有帖子修订以及与之关联的元。 您必须在WordPress数据库上运行以下查询,所有版本(以及与其关联的元数据)都将从数据库中删除。 这里的一个重要说明是,在运行代码之前,请确保对数据库进行备份。
DELETE a,b,c
FROM wp_posts a
WHERE a.post_type = 'revision'
LEFT JOIN wp_term_relationships b
ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id);
[来源: Lesterchan.net ]
13.根据类别更改摘录长度
是否曾经希望根据您所在的类别来修改摘录长度? 这是实现您愿望的代码。 只需将代码粘贴到您的functions.php文件中,别忘了更改第3行的类别ID !
add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($length) {
if(in_category(14)) {
return 13;
} else {
return 60;
}
}
[来源: WpRecipes ]
14.禁用帖子自动保存
如果出于某些重要原因,您想要在仪表板中编辑帖子时禁用自动保存帖子的功能,则可以这样做。 只需打开您的functions.php文件并将以下代码粘贴到该文件中:
function disableAutoSave(){
wp_deregister_script('autosave');
}
add_action( 'wp_print_scripts', 'disableAutoSave' );
[来源: WpRecipes ]
然后,您可以保存文件,WordPress将永远不会自动保存帖子。 您也可以通过删除代码来找回功能。
翻译自: https://www.hongkiat.com/blog/wordpress-tweaks-for-post-management/