我在帖子中有一个元数据(一个复选框),用于检查是否会发布帖子。
我的代码:
function add_featured_post_checkbox() {
add_meta_box(
'custom_featured_meta',
'Featured post for Sidebar',
'featured_post_checkbox_callback',
'Post',
'side',
'high'
);
} add_action( 'add_meta_boxes', 'add_featured_post_checkbox' );
回调功能:
function featured_post_checkbox_callback( $post ) {
wp_nonce_field( 'custom_save_data' , 'custom_featured_nonce' );
$featured = get_post_meta($post->ID, '_featured_post', true);
echo "<label for='_featured_post'>".__('Is Featured? ', 'foobar')."</label>";
echo "<input type='checkbox' name='_featured_post' id='featured_post' value='1' " . checked(1, $featured) . " />";
}
保存功能:
function custom_save_data( $post_id ) {
if( ! isset( $_POST['custom_featured_nonce'] ) ){
return;
}
if( ! wp_verify_nonce( $_POST['custom_featured_nonce'], 'custom_save_data') ) {
return;
}
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if( ! isset( $_POST['_featured_post'] ) ) {
return;
}
$my_data_featured = sanitize_text_field( $_POST['_featured_post'] );
update_post_meta( $post_id, '_featured_post', $my_data_featured );
} add_action( 'save_post', 'custom_save_data' );
此代码仅在我想要发布帖子时才有效。
例如,如果帖子没有被选中作为精选,我选择了选择然后数据库更新完美(post_meta中的值为1)并且ckeckbox在框上打勾
但之后,如果我尝试取消选中并保存帖子,那么ckeckbox再次带有勾号,数据库中没有任何变化..
我尝试在stackoverflow上找到一个解决方案,在网络上找到一般但我找不到。
请帮帮我
谢谢
答案 0 :(得分:2)
取消选中复选框后,$_POST
将不会包含密钥_featured_post
。因此,在保存回调中,您需要更改策略。如果没有设置密钥,你不想拯救。相反,您要么保存0或删除帖子元。让我们选择后一个选项。
function custom_save_data( $post_id ) {
if( ! isset( $_POST['custom_featured_nonce'] ) ){
return;
}
if( ! wp_verify_nonce( $_POST['custom_featured_nonce'], 'custom_save_data') ) {
return;
}
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( isset( $_POST['_featured_post'] ) ) {
update_post_meta( $post_id, '_featured_post', 1 );
} else {
delete_post_meta( $post_id, '_featured_post' );
}
}
请注意,您无需使用sanitize_text_field()
。为什么?因为该值只是1
。就是这样。在这里,我们可以硬编码该值。
运行代码我看到在检查时,checked=checked
的HTML正在呈现为文本。为什么?因为运行函数checked()
会将其回显给浏览器,除非你告诉它不要。您必须检查您的代码:
checked(1, $featured, false);
答案 1 :(得分:1)
由于检查后是否在_featured_post
数组中设置了$_POST
,因此发生了这种情况。如果不选中该复选框,则不会设置。你的方法应该是下一步
if (isset($_POST['_featured_post']))
{
update_post_meta($object_id, '_featured_post', 1); // can only be 1 when checked anyway
}
else
{
delete_post_meta($object_id, '_featured_post');
}