publish\\u post在发布帖子时运行,或者如果帖子已编辑且其状态为“published”。操作函数参数:post ID。
我已经将publish\\u post挂钩添加到我正在编写的WordPress插件中。钩子本身调用的函数旨在使用wp\\u update\\u post函数更改几个帖子的类别。
但是,此挂钩不起作用,因为运行wp\\u update\\u post返回的结果始终为0。我的猜测是,运行wp\\u update\\u post会导致另一个钩子实例运行,因为它会重新发布帖子。。。我相信这会带来"...or if it is edited and its status is "published"" 上述声明的一部分。
有没有其他我可以使用的动作挂钩,只有在添加的帖子是全新的且未编辑时才会调用?
<?php
/*
Plugin Name: Category Switcher Plugin
Plugin URI: http://www.example.com
Description: When a new post is created this plugin will cause the
Version: 0.1
Author: Me
License: GPL2
?>
<?php
class categoryShifter {
function shiftCategories($post_ID) {
$maxNumPostsFirstTeir = 4;
$first_teir_cat = "Fresh News Stories 1";
$second_teir_cat = "Slightly Dated Stories 2";
$firephp = FirePHP::getInstance(true);
$firephp->info(\'BEGIN: categoryShifter.shiftCategories()\');
$firephp->log($post_ID, \'post_ID: \');
$firephp->trace(\'trace to here\');
$first_teir_id = categoryShifter::getIDForCategory($first_teir_cat, $firephp);
$second_teir_id = categoryShifter::getIDForCategory($second_teir_cat, $firephp);
$firephp->log($first_teir_id, \'$first_teir_id\');
$firephp->log($second_teir_id, \'$second_teir_id\');
$qPostArgs = array(
\'numberposts\' => 100,
\'order\' => \'DESC\',
\'orderby\' => \'post_date\',
\'post_type\' => \'post\',
\'post_status\' => \'published\',
\'category_name\' => $first_teir_cat
);
$firstTeirPosts = get_posts($qPostArgs);
$firephp->log($firstTeirPosts, \'got posts:\');
$firephp->log(sizeof($firstTeirPosts), \'sizeof\');
// NOTE: This appears to work.
for($i = sizeof($firstTeirPosts)-1; $i > $maxNumPostsFirstTeir-4; $i--)
{
$newCats = array($second_teir_id);
$editingId = $firstTeirPosts->ID;
$result = wp_set_post_categories($editingId, $newCats); /* NOTE: Doesn\'t work presently... returns an array with the $second_teir_id in it. */
$firephp->log($result, \'Result\');
}
/*
$my_post = array();
$my_post[\'ID\'] = 132;
$my_post[\'post_category\'] = array($second_teir_id);
$firephp->log(\'Before\', \'Before\');
if(wp_update_post( $my_post ) == 0) {
$firephp->Error(\'Fatal Error, Post not updated\', \'error\');
}
$firephp->log(\'After\', \'After\');
*/
return $post_ID;
}
function getIDForCategory($cat_name, $logger) {
$logger->Info("Begin: getIDForCategory()");
$cats = get_categories();
$whichCatId = "";
foreach($cats as $single_cat) {
if($single_cat->name == $cat_name) {
$whichCatId = $single_cat->term_id;
break;
}
}
$logger->Info("End: getIDForCategory()");
return (int)$whichCatId;
}
}
/* Hook Post Creation */
/* add_action(\'publish_post\', array(\'categoryShifter\',\'shiftCategories\')); */
add_action(\'wp_insert_post\', array(\'categoryShifter\', \'shiftCategories\'));
?>
我暂时改用wp\\u insert\\u post挂钩。。。但是我仍然无法使用wp\\u set\\u post\\u categories函数来更改帖子的类别。我知道我可能需要更新这段代码,以便它考虑到帖子的现有类别,并且只修改插件指定的类别,但现在它实际上只是一个alpha。