【问题标题】:Validate custom fields in wordpress post验证 wordpress 帖子中的自定义字段
【发布时间】:2014-05-27 18:09:43
【问题描述】:

我有一个自定义帖子类型speaker,在扬声器中我有一个自定义字段speaker_organization。如何验证这一点并在admin notice 中显示错误。

add_action( 'add_meta_boxes', 'speaker_organization_box' );
function speaker_organization_box() {
    add_meta_box( 
        'speaker_organization',
        __( 'Organization', 'dbem' ),
        'speaker_organization_box_content',
        'speaker',
        'side',
        'high'
    );
}

function speaker_organization_box_content( $post ) {
    // generate a nonce field
    wp_nonce_field( basename( __FILE__ ), 'dbem-speaker-organization-nonce' );

    // get previously saved meta values (if any)
    $speaker_organization = get_post_meta( $post->ID, 'speaker_organization', true );

    echo '<label for="speaker_organization"></label>';
    echo '<input type="text" id="speaker_organization" name="speaker_organization" placeholder="Organization Name" value="'.$speaker_organization.'" />';
}

function speaker_organization_box_save( $post_id ) {
  $speaker_organization = $_POST['speaker_organization'];
  update_post_meta( $post_id, 'speaker_organization', $speaker_organization ); 
}
add_action( 'save_post', 'speaker_organization_box_save' );

【问题讨论】:

标签: php wordpress wordpress-theming


【解决方案1】:

使用

add_action('admin_notices', 'my_admin_notice');

或使用验证 js

add_action('admin_enqueue_scripts', 'add_my_js');   
function add_my_js(){    
  wp_enqueue_script('my_validate', 'path/to/jquery.validate.min.js', array('jquery'));
  wp_enqueue_script('my_script_js', 'path/to/my_script.js');
}

jQuery().ready(function() {
    jQuery("#post").validate();
});

<input type="text" name="my_custom_text_field" class="required"/>

function wpse_update_post_custom_values($post_id, $post) {
    // Do some checking...
    if($_POST['subhead'] != 'value i expect') {
        // Add an error here
        $errors->add('oops', 'There was an error.');
    }
    return $errors;
} 
add_action('save_post','wpse_update_post_custom_values',1,2);

validate js code

using condition + admin notice

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 2014-01-23
    • 1970-01-01
    • 2021-11-30
    • 2011-08-11
    • 2014-03-02
    • 2015-10-24
    相关资源
    最近更新 更多