在WordPress中,如果你想在编辑文章的时候自动将某个字段(比如日期)修改为当前时间,你可以使用save_post钩子来实现这一功能。以下是一个示例代码,它会在保存文章的时候自动将日期字段设置为当前时间:
// 确保此代码在functions.php或插件文件中
// 钩子函数,在保存文章时触发
function auto_update_post_date($post_id) {
if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE ) {
return;
}
// 确保当前用户有权限编辑文章
if ( ‘page’ == $_POST[‘post_type’] ) {
if ( !current_user_can( ‘edit_page’, $post_id ) )
return;
} else {
if ( !current_user_can( ‘edit_post’, $post_id ) )
return;
}
// 设置文章的日期为当前时间
$post = get_post( $post_id );
$current_date = current_time( ‘mysql’ );
$post->post_date = $current_date;
wp_update_post( array( ‘ID’ => $post_id, ‘post_date’ => $current_date ) );
}
// 添加钩子
add_action( ‘save_post’, ‘auto_update_post_date’ );

将上述代码添加到你的WordPress主题的functions.php文件中,或者如果你在编写插件,则将其添加到插件文件中。这段代码会在每次保存文章时检查,如果不是自动保存,并且当前用户有权限编辑文章,就会自动将文章的日期设置为当前时间。

请注意,这段代码没有考虑文章的其他状态,如是否为自动保存(DOING_AUTOSAVE)、是否为草稿(post_statusdraft),或是否正在使用某些特定的插件可能会影响这一行为。在实际使用时,你可能需要根据具体情况调整代码。

 

 

// 确保此代码在functions.php或插件文件中

// 钩子函数,在保存文章时触发
function auto_update_post_date( $post_id ) {
if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE ) {
return;
}

// 确保当前用户有权限编辑文章
if ( ‘page’ == $_POST[‘post_type’] ) {
if ( !current_user_can( ‘edit_page’, $post_id ) )
return;
} else {
if ( !current_user_can( ‘edit_post’, $post_id ) )
return;
}

// 设置文章的日期为当前时间
$post = get_post( $post_id );
$current_date = current_time( ‘mysql’ );
$post->post_date = $current_date;
wp_update_post( array( ‘ID’ => $post_id, ‘post_date’ => $current_date ) );
}

// 添加钩子
add_action( ‘save_post’, ‘auto_update_post_date’ );

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。