我想在自定义字段中为CPT设置一个数字计数器,有点像post ID,但只针对该自定义post类型,从1开始。我试图在第一次创建帖子时,从选项中的递增值开始设置自定义字段值。
我试图在新帖子保存时调用此函数并递增,但当帖子保存/更新时,它会继续写入它,等等,所以我使用了错误的钩子,但似乎找不到正确的钩子。
// Maintain Asset register count in Options Table and assign to new assets
function define_asset( $post_id, $post ) {
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) return;
if ( ! current_user_can( \'edit_post\', $post_id ) ) return;
global $wpdb;
$isAsset = get_post_meta($post_id, \'assetID\', false);
if ($isAsset ) {
if(get_option(\'assetID\')){
$count = get_option(\'assetID\', true);
update_option(\'assetID\', $count+1);
$assetID = get_option(\'assetId\');
str_pad($assetID, 5, \'0\', STR_PAD_LEFT);
} else {
/** This will automatically add the option if it does not exist. **/
update_option(\'assetID\', 1); // adding first time as value 1
}
$assetID = str_pad($assetID, 5, \'0\', STR_PAD_LEFT);
update_post_meta( $post_id, \'assetID\', $assetID );
}
}
//add_action( \'post_updated\', \'define_asset\', 20, 2 );
add_action( \'save_post\', \'define_asset\', 20, 2 ); // This works but increments on each save
//add_action( \'publish_post\', \'define_asset\', 20, 2 ); // This works but increments on each save
//add_action( \'publish_inventory\', \'define_asset\', 20, 2 ); //
//add_action( \'draft_to_published\', \'define_asset\', 20, 2 ); // This doesn\'t work