I've written a wordpress plugin that requires our writers to pick a topic from an external site. It will not allow the writer to publish the article unless a topic from the external site is associated with it. When the article is published, the topic they chose is updated on the external site and, therefore, on an option to select again.
This all works as expected. My problem is that when a user updates an article that has already been published, and therefore, the topic is no longer an option to choose, the plugin stops them from updating because there is no topic.
My question is: Is there a way to ensure the plugin only runs when a post is initially published, not when it is updated?
Here is the code (with parts removed):
<?php
*/
Plugin Name: name
Description: Make sure writers articles are associated with a name topic.
*/
add_action('add_meta_boxes','name_add_meta_boxes');
add_action('save_post', 'complete_name_topic');
function name_add_meta_boxes() {
add_meta_box(
'name',
'name',
'name_html',
'post',
'normal'
);
}
function name_html($post){
wp_nonce_field(plugin_basename(__FILE__), 'name_nonce');
$current_user = wp_get_current_user();
$f_name = utf8_encode($current_user->user_firstname);
$l_name = utf8_encode($current_user->user_lastname);
if(!$f_name || !$l_name){
$display_name = str_replace(' ', '%20', $current_user->display_name);
}else{
$display_name = $f_name.'%20'.$l_name;
}
$bar = json_decode(www.example.com));
$foo = get_object_vars($bar);
echo '<select name="name"><option value="">Choose name Topic</option>';
foreach($foo as $id => $topic){
echo "<option value='$id'>$topic</option>";
}
echo '</select>';
}
function complete_name_topic($post_id) {
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if(!wp_verify_nonce($_POST['name_nonce'], plugin_basename(__FILE__)))
return;
$id = wp_is_post_revision($post_id);
if(!$id){
$permalink = get_permalink($post_id);
}else{
$permalink = get_permalink($id);
}
if(!isset($_POST['name']) || empty($_POST['name'])){
$message = 72;
global $wpdb;
$wpdb->update($wpdb->posts, array('post_status' => 'pending'), array('ID' => $post_id));
add_filter('redirect_post_location', create_function('$location', 'return add_query_arg("message", "'.$message.'", $location);'));
}else{
$ch = curl_init('www.example.com');
curl_setopt($ch, CURLOPT_POSTFIELDS, "URL=$permalink");
curl_exec($ch);
curl_close($ch);
}
}
add_filter('post_updated_messages', 'name_error_message');
function name_error_message($messages){
$messages['post']['**'] = 'A name topic must be associated with this post.';
return $messages;
}