• Resolved toms17

    (@toms17)


    Hi,

    I’ve been struggling with this problem for quite some time now and I’ve finally decided to make a post here on the forum.

    The general idea of what I’m trying to do is create some code that automatically adds a NEW icon to the end of each post title if it is not older than 3 days. I have tried several different approaches to this including the approach below using a post_query. I have also tried the approach found on this website: Website but have had no luck.

    The below code is the closest I have come to get this to work. However, it adds the icon to all posts if one post in that query is not older than 3 days.

    function new_icon_title($title){
       	if (in_category('all-surgery') && is_page()){
       		$title = $title . ' <img src="https://maxcdn.icons8.com/Color/PNG/24/Ecommerce/new-24.png" title="New" width="24">';
       	}
       	return $title;
    }
    
    function add_new_icon(){
    
    		$args = array(
    				'post_type' => 'post',
    				'category_name' => 'all-surgery',
    				'date_query' => array(
    						'after' => date('Y-m-d', strtotime('-3 days'))
    		)
    		);
    
    		$post_query = new WP_Query($args);
    
    		if($post_query->have_posts()){
    			while($post_query->have_posts()){
    				if('date_query'){
    					add_filter('the_title', 'new_icon_title');
    					return;
    				}
    
    			}
    		}
    	}
    
    add_action('init', 'add_new_icon');

    Any help would be very much appreciated.

    Thank you.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi, @toms17, what about using something like this:

    add_filter('the_title', 'add_to_title');
    
    function add_to_title($title) {
    	if ( in_the_loop() && !is_old_post(3) && in_category('all-surgery') && is_page() ) {
    		$title = $title . ' <img src="https://maxcdn.icons8.com/Color/PNG/24/Ecommerce/new-24.png" title="New" width="24">';
       	}
    
       	return $title;
    
    }
    
    function is_old_post($days = 5) {
    	$days = (int) $days;
    	$offset = $days*60*60*24;
    
    	if ( get_post_time() < date('U') - $offset )
    		return true;
    
    	return false;
    }

    IMPORTANT: While I included your in_category('all-surgery') && is_page() conditional in my example, categories can’t be assigned to pages in WordPress by default, so unless you’ve done something to make that possible, the conditional would always evaluate to FALSE (and thus, you’d want to modify it).

    Thread Starter toms17

    (@toms17)

    Hi, @girlieworks, this worked perfectly! Many thanks for this.

    @toms17: I’m glad to hear that, you’re welcome! 🙂

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Edit Post Title when not older than 3 days’ is closed to new replies.