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;
}
这是一个很好的解决方案。我唯一的问题是我还需要它忽略已存在的帖子。在我添加该行代码之前,他们不会像设置完成一样设置meta_data。所以他们会像以前一样继续,造成一个问题。 – 2012-03-09 16:08:31
我明白你的意思了。在插件安装中更新所有现有帖子的元数据是一种可能性,尽管不是很吸引人。那么比较帖子的post_date和插件的安装时间呢? – dldnh 2012-03-09 17:21:18
这会起作用,但我对wordpress很陌生(这是我的第一个插件),我不确定如何访问插件的安装时间。我知道我可以挂钩激活并设置一些东西,但我不确定在哪里设置它,因此范围超出了插件的存在范围。我试着使用'publish_post',然后在继续之前(如果它是更新)检查'if(get_post_status('$ id')== publish)'但它总是被发现是真的。我想它是在运行插件之前更新状态。现在我正在关注'wp_transition_post_status'。 – 2012-03-09 19:45:43