2012-03-09 99 views
2

我寫了一個wordpress插件,要求我們的作者從外部網站選擇一個主題。除非外部網站的主題與其相關聯,否則它不允許作者發佈文章。文章發佈後,他們選擇的主題會在外部網站上更新,因此會再次選擇一個選項。
這一切都按預期工作。我的問題是,當用戶更新已發佈的文章,並且因此該主題不再是可供選擇的選項時,插件會阻止它們不進行更新,因爲沒有主題。
我的問題是:有沒有辦法確保插件只在最初發布帖子時運行,而不是在更新時運行?是否有可能使wordpress插件僅在發佈時運行,而不是在更新上運行?

下面是代碼(有部分刪除):

<?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; 
} 

回答

0

如果update_post_meta第一次通過,你可以get_post_meta發現是否已發生的後續更新。

+0

這是一個很好的解決方案。我唯一的問題是我還需要它忽略已存在的帖子。在我添加該行代碼之前,他們不會像設置完成一樣設置meta_data。所以他們會像以前一樣繼續,造成一個問題。 – 2012-03-09 16:08:31

+0

我明白你的意思了。在插件安裝中更新所有現有帖子的元數據是一種可能性,儘管不是很吸引人。那麼比較帖子的post_date和插件的安裝時間呢? – dldnh 2012-03-09 17:21:18

+0

這會起作用,但我對wordpress很陌生(這是我的第一個插件),我不確定如何訪問插件的安裝時間。我知道我可以掛鉤激活並設置一些東西,但我不確定在哪裏設置它,因此範圍超出了插件的存在範圍。我試着使用'publish_post',然後在繼續之前(如果它是更新)檢查'if(get_post_status('$ id')== publish)'但它總是被發現是真的。我想它是在運行插件之前更新狀態。現在我正在關注'wp_transition_post_status'。 – 2012-03-09 19:45:43

相關問題