【问题标题】:How to add an image dynamically to post title if it is published today or less than 2 days如果今天发布或不到 2 天,如何将图像动态添加到帖子标题
【发布时间】:2026-02-17 07:10:01
【问题描述】:

我试图在刚刚发布且不到 2 天的帖子中添加类似“新”图像的图像。

我尝试在 WP_Query 中使用这样的函数,但它适用于所有帖子。

add_action('the_title', 'insiderable_add_img_new');
function insiderable_add_img_new($title) {
    $title = '<img src="https://example.com/icon.gif">'.$title;
    return $title;
}

这是我对 WP_Query 的尝试:

$events_query = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'posts_per_page'=>-1)); 
if($events_query->have_posts()) : 
    while($events_query->have_posts()) : 
       $events_query->the_post();
       if (get_the_date( 'Y-m-d' ) === date( 'Y-m-d' )) {
        add_filter('the_title', 'insiderable_add_img_new');
    }
endwhile; else: endif;
wp_reset_postdata();
function insiderable_add_img_new($title) {
    $title = '<img src="https://example.com/icon.gif">'.$title;
    return $title;
}

【问题讨论】:

    标签: php wordpress wordpress-theming wordpress-gutenberg genesis


    【解决方案1】:

    此代码 sn-p 检查所有帖子,如果日期匹配今天,它会修改 $title。

    我正在寻找更高效的代码,如果你有,请建议。

    把这个sn-p放在最下面的functions.php中:

    // Working Model 
    add_filter( 'the_title', 'ag_custom_post_title_link' );
    function ag_custom_post_title_link( $title ) {
        $postdate = get_the_date( 'Y-m-d' );
    $nows = date( 'Y-m-d' );
        if ( $postdate == $nows) {
            $title = '<img src="https://example.com/img.gif">'.$title;
        }
        return $title;
    }
    

    您还可以对其进行编辑以应用:如果帖子不到 2 天或类似情况。

    我认为这对某人有帮助:)

    【讨论】: