我想在最近帖子的小部件标题中添加一个“新”徽章。每当我在5天内添加任何新帖子时,这个“新”徽章就会显示出来,之后它就会消失。此徽章是一个“new.gif”文件。我还添加了一张图片供您参考。
如何向WordPress中最近发布的帖子小工具中显示的帖子标题添加徽章“new”
2 个回复
最合适的回答,由SO网友:Electronic Ink 整理而成
这应该能帮你解决问题。我已经尽可能多地发表了评论:)将下面的代码放在函数中。php文件。
function your_recent_posts_by_category_with_badge() {
// WP_Query arguments
$args = array(
\'category_name\' => \'catname-1, catname-2\',
//\'cat\' => 5,
//\'tag\' => \'tagname\',
//\'tag_id\' => 5,
\'posts_per_page\' => 10
);
// Set today\'s date
$the_date_today = date(\'r\');
// Create WP_Query instance
$the_query = new WP_Query( $args );
// Check for posts
if ( $the_query->have_posts() ) {
// Set up HTML list & CSS classes for styling
echo \'<ul class="recentcategorybadgeposts widget_recent_entries">\';
// Loop through each post
// Default is latest posts
while ( $the_query->have_posts() ) {
$the_query->the_post();
// Compare post date from todays date
$each_post_date = get_the_time(\'r\');
$difference_in_days = round( ( strtotime( $the_date_today ) - strtotime( $each_post_date) ) / ( 24 * 60 * 60 ), 0 );
// Condition set for 5 days
if ( $difference_in_days >= 5 ) {
// If less than 5 days show IMG tag
echo \'<li><a href="\' . get_the_permalink() .\'">\' . get_the_title() .\'</a><img src="new.gif"></li>\';
} else {
// Else no show
echo \'<li><a href="\' . get_the_permalink() .\'">\' . get_the_title() .\'</a></li>\';
}
} // end while
// Close list
echo \'</ul>\';
} // endif
// Reset Post Data
wp_reset_postdata();
}
// Add a shortcode to use anywhere within your website
add_shortcode(\'recentcategorybadgeposts\', \'your_recent_posts_by_category_with_badge\');
// Enable shortcodes in text widgets
// Add a \'Text Widget\' to your sidebar then in the input field, paste [recentcategorybadgeposts]
add_filter(\'widget_text\', \'do_shortcode\');
SO网友:Electronic Ink
您可以编写自己的插件来创建一个独特的最近帖子小部件,如下所示:https://themefuse.com/how-to-create-a-recent-posts-wordpress-plugin/
在教程中标题为“插件功能”的部分中,将代码更改为:
<ul>
<?php
global $post;
$today = date(\'r\');
$args = array( \'numberposts\' => $dis_posts);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
$articledate = get_the_time(\'r\');
$difference = round((strtotime($today) - strtotime($articledate))/(24*60*60),0);
if ($difference >= 5) { ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><img src="new.gif"></li>
<?php } else { ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php }
endforeach; ?>
</ul>