选中“通知”复选框时显示通知的代码片段,并在管理中的更新和发布帖子或页面中显示消息
function cabtv_add_post_options()
{
// Add our meta box for the "post" post type (default)
$post_types = array("post", "page");
foreach ($post_types as $post_type) {
add_meta_box(\'cabtv_notif_on_post\',\'Notifications\',\'cabtv_notif_on_post_html_view\',$post_type,\'side\',\'high\');
}
}
add_action(\'add_meta_boxes\', \'cabtv_add_post_options\');
function cabtv_notif_on_post_html_view($post)
{
wp_nonce_field( \'cabtv_notif_metabox\', \'cabtv_notif_metabox\' );
$checked = get_post_meta( $post->ID, \'cabtv_notifications_sent\', true);
$check = $checked?\'checked\':\'\';
if ($checked) { ?>
<div style=\'padding:10px;\'>
<span style=\'color:red; font-weight:bold;\'>Notifications have already been sent for this post.</span>
</div>
<?php } ?>
<input type="hidden" name="cabtv_meta_box_present" value="true"></input>
<input type="checkbox" name="cabtv_send_notification" value="true" <?php echo $check; ?>></input>
<label>
<?php echo esc_attr(\'Send notification on \'.($post->post_status === \'publish\' ? \'update\' : \'publish\') ); ?>
</label>
<?php
}
function save_notice_meta_box_data( $post_id ) {
// Check if our nonce is set.
if ( ! isset( $_POST[\'cabtv_notif_metabox\'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST[\'cabtv_notif_metabox\'], \'cabtv_notif_metabox\' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don\'t want to do anything.
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user\'s permissions.
if ( isset( $_POST[\'post_type\'] ) && \'page\' == $_POST[\'post_type\'] ) {
if ( ! current_user_can( \'edit_page\', $post_id ) ) {
return;
}
}
else {
if ( ! current_user_can( \'edit_post\', $post_id ) ) {
return;
}
}
/* OK, it\'s safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST[\'cabtv_send_notification\'] ) ) {
return;
}
// Sanitize user input.
$my_data = sanitize_text_field( $_POST[\'cabtv_send_notification\'] );
// Update the meta field in the database.
update_post_meta( $post_id, \'cabtv_notifications_sent\', $my_data?$my_data:\'\');
}
add_action( \'save_post\', \'save_notice_meta_box_data\' );
**save\\u notice\\u meta\\u box\\u数据函数代码解释:**
//检查我们的nonce是否已设置。
if ( ! isset( $_POST[\'cabtv_notif_metabox\'] ) ) {
return;
}
//检查用户的权限。
if ( isset( $_POST[\'post_type\'] ) && \'page\' == $_POST[\'post_type\'] ) {
if ( ! current_user_can( \'edit_page\', $post_id ) ) {
return;
}
}
else {
if ( ! current_user_can( \'edit_post\', $post_id ) ) {
return;
}
}
//确保已设置。
if ( ! isset( $_POST[\'cabtv_send_notification\'] ) ) {
return;
}
//更新数据库中的元字段。
update_post_meta( $post_id, \'cabtv_notifications_sent\',$my_data);
//保存帖子和页面挂钩
add_action( \'save_post\', \'save_notice_meta_box_data\' );