【问题标题】:How to add checkbox and make some function running如何添加复选框并使某些功能运行
【发布时间】:2018-03-13 04:22:38
【问题描述】:

您能否帮助在 wordpress 的发布帖子中添加复选框,如果选中复选框,则某些功能将运行。

【问题讨论】:

标签: php wordpress


【解决方案1】:

请查看此代码

add_action('post_submitbox_misc_actions', 'createCustomField');

add_action('save_post', 'saveCustomField');

function createCustomField()
{
    $post_id = get_the_ID();

    if (get_post_type($post_id) != 'post') {
        return;
    }

    $value = get_post_meta($post_id, '_my_custom_field', true);
    wp_nonce_field('my_custom_nonce_'.$post_id, 'my_custom_nonce');
    ?>
    <div class="misc-pub-section misc-pub-section-last">
        <label><input type="checkbox" value="1" <?php checked($value, true, true); ?> name="_my_custom_field" /><?php _e('My Custom Checkbox Field', 'pmg'); ?></label>
    </div>
    <?php
}

function saveCustomField($post_id)
{
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    if (
        !isset($_POST['my_custom_nonce']) ||
        !wp_verify_nonce($_POST['my_custom_nonce'], 'my_custom_nonce_'.$post_id)
    ) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    if (isset($_POST['_my_custom_field'])) {
        update_post_meta($post_id, '_my_custom_field', $_POST['_my_custom_field']);
    } else {
        delete_post_meta($post_id, '_my_custom_field');
    }
}

希望对您有所帮助。

【讨论】:

  • sry 无法为反馈添加投票,因为新成员:D
猜你喜欢
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-26
  • 1970-01-01
  • 2019-10-16
  • 2020-11-10
相关资源
最近更新 更多