第一个问题是$post
不在回调的范围内。您需要修改代码以将其引入:
function only_one_agenda_featured( $post_id, $post ) {
// ...
}
add_action( \'save_post\', \'only_one_agenda_featured\' ,10, 2);
考虑到这种变化,情况应该会更好,但代码过于复杂。除非你需要一段历史
agenda_featured
发布时,只需删除旧字段,然后设置新字段。
function only_one_agenda_featured( $post_id, $post ) {
// If this isn\'t a \'agenda\' post, don\'t update it.
if ( \'agenda\' != $post->post_type ) {
return;
}
// Stop when it is an autosave
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) {
return;
}
// Prevent quick edit from clearing custom fields
if (defined(\'DOING_AJAX\') && DOING_AJAX) {
return;
}
if (!empty($_POST[\'agenda_featured\']) && true == $_POST[\'agenda_featured\']) {
// delete
delete_metadata ( \'agenda\', null, \'agenda_featured\', null, true );
// and insert
add_post_meta( $post_id, \'agenda_featured\', true);
}
}
add_action( \'save_post\', \'only_one_agenda_featured\' ,10, 2);
通过使用
post-type specific hook:
3580 do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
类似于:
function only_one_agenda_featured( $post_id, $post ) {
// Stop when it is an autosave
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) {
return;
}
// Prevent quick edit from clearing custom fields
if (defined(\'DOING_AJAX\') && DOING_AJAX) {
return;
}
if (!empty($_POST[\'agenda_featured\']) && true == $_POST[\'agenda_featured\']) {
// delete
delete_metadata ( \'agenda\', null, \'agenda_featured\', null, true );
// and insert
add_post_meta( $post_id, \'agenda_featured\', true);
}
}
add_action( \'save_post_agenda\', \'only_one_agenda_featured\' ,10, 2);
使用直接SQL可以使删除/保存更加高效,但我像个好孩子一样坚持使用核心函数;)