Skip to content

Instantly share code, notes, and snippets.

@Jonnyauk
Created June 25, 2012 14:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jonnyauk/2989039 to your computer and use it in GitHub Desktop.
Save Jonnyauk/2989039 to your computer and use it in GitHub Desktop.
Detect if WordPress post is published for the first time
<?php
/*
* On first publish set a special date in advance in custom field
*/
add_action('transition_post_status','tanc_first_schedule_publish_set',10,3);
function tanc_first_schedule_publish_set($new, $old, $post) {
// REFERENCE
// $new = new post status ('publish')
// $old = old post status ('draft')
// $post = Post Object ($post->ID)
// On first publish
if ($new == 'publish' && $old != 'publish' && isset($post->post_type)) {
switch ($post->post_type) {
case 'type_one' :
update_post_meta( $post->ID, 'type_one_expiry_date', strftime( '%Y-%m-%d', (strftime('%Y-%m-%d', time()) + strtotime('+365 days')) ) );
break;
case 'type_two' :
update_post_meta( $post->ID, 'type_one_expiry_date', strftime( '%Y-%m-%d', (strftime('%Y-%m-%d', time()) + strtotime('+31 days')) ) );
break;
default:
// Silence is golden
break;
}
}
}
?>
@hoffmana
Copy link

hoffmana commented Feb 9, 2023

Hi,
I am looking for some code to save the date, when a post is published for the first time. I think your code might help me perfectly.
How do I include this code to my installation? Do I add it into the functions.php in my child theme?
And how do I add a custom filed. With the plugin Advanced Cutsom fields? How should the field be named? Any restrictions or recommendations?

I really appreciate your help. Thanks a lot.

Best regards, Thomas

@mustardBees
Copy link

Huh, look who just showed up in my Google search results... works perfectly. Thanks @Jonnyauk 👋

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment