在发布未发布的草稿时,我希望将自定义元值“post views count”设置为介于829
和1013
.
我正在使用下面的代码,但并不总是有效。当我create a test draft and publish it immediately, 但是,当我把一篇文章保存几天或分配给其他作者时,它就不起作用了。
注意:我不想创建新的自定义字段。我只想更新现有字段,该字段名为post_views_count
.
function wpse_custom_field_on_publish( $new, $old, $post ) {
if ( $new == \'publish\' && $old != \'publish\' && !get_post_meta( $post->ID, \'post_views_count\', true ) ) {
update_post_meta( $post->ID, \'post_views_count\', rand(829, 1013), true );
}
}
add_action( \'transition_post_status\', \'wpse_custom_field_on_publish\', 10, 3 );
SO网友:Domain
您的代码略有更改,
function wpse_custom_field_on_publish( $new, $old, $post ) {
// Only run on "from X > to publish"-transitions
if ( $new === \'publish\' && $old !== \'publish\') {
$page_views = get_post_meta( $post->ID, \'post_views_count\', true );
// Only set \'post_views_count\' post meta value if there is none so far
if ( empty( $page_views ) )
update_post_meta( $post->ID, \'post_views_count\', rand( 829, 1013 ) );
}
}
add_action( \'transition_post_status\', \'wpse_custom_field_on_publish\', 10, 3 );