php 自定义元字段的自定义帖子类型

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 自定义元字段的自定义帖子类型相关的知识,希望对你有一定的参考价值。

<?php
$category = get_post_meta( $post->ID, '_category', true );  // gets the meta data if it already exists
$categories = array(
  'news' => 'News',
  'juveniles' => 'Safety of Juveniles',
  'families' => 'Family Separations',
);
?>
<label for="_category">Categories:</label> <br />
<?php
foreach( $categories as $id => $option ) {
    if ( is_array( $category ) && in_array( $id, $category ) ) {
        $checked = 'checked="checked"';
    } else {
        $checked = null;
    }
    ?>
    <label for="_category[<?php echo $id;?>]"><input type="checkbox" name="_category[]" value="<?php echo $id;?>" id="_category[<?php echo $id;?>]" <?php echo $checked; ?> /> <?php echo $option;?></label> <br />
    <?php
}

function save__news__meta( $post_id, $post ) {
  // return if the user doesn't have edit permissions.
  if ( ! current_user_can( 'edit_post', $post_id ) ) {
      return $post_id;
  }
  // return unless nonce is verified
  if ( ! isset( $_POST['news__meta_nonce'] ) || ! wp_verify_nonce( $_POST['news__meta_nonce'], basename(__FILE__) ) ) {
      return $post_id;
  }

  if ( ! empty( $_POST['_category'] ) ) {
      update_post_meta( $post_id, '_category', $_POST['_category'] );

  // Otherwise just delete it if its blank value.
  } else {
      delete_post_meta( $post_id, '_category' );
  }
}
<?php
// outputs a text field with datepicker
wp_enqueue_script( 'jquery-ui-datepicker' );
wp_enqueue_style( 'jquery-ui-style', '//ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/smoothness/jquery-ui.css', true);
?>
<script>
    jQuery(document).ready(function(){
        jQuery('.date_picker').datepicker({
            dateFormat : 'yy-mm-dd'
        });
    });
</script>
<?php
echo '<p>This is a good place for helper text.</p>';
echo'<label for="_meta_field">Meta Field</label>';
echo '<input type="text" name="_meta_field" value="' . esc_textarea( $metaField ) . '" class="widefat date_picker" id="_meta_field">';
// outputs a dropdown box with dynamic options via wp_query
echo '<p>This is a good place for helper text.</p>';
echo'<label for="_meta_field">Meta Field</label>'; 
?>
<select name="_meta_field" id="_meta_field" class="widefat">
    <?php
    $metaFieldVar = $metaField;  // stores $metaField data so it can be used inside the wp_query
    $meta_options = new WP_Query(array( 
        'post_type' => array('queried_post_type'),
        'nopaging' => true,
        'orderby'=> 'title', 
        'order' => 'ASC'
    ));
    while( $meta_options->have_posts() ){
        $meta_options->the_post(); 
        ?> 
        <option value="<?php the_title(); ?>" <?php selected( $metaFieldVar, get_the_title() ); ?>><?php the_title(); ?></option> 
        <?php
    } 
    ?>
</select>
<?php
wp_reset_postdata();
$post = $originalpost;
<?php
// outputs a dropdown box with static options
echo '<p>This is a good place for helper text.</p>';
echo'<label for="_meta_field">Meta Field</label>'; 
?>
<select name="_meta_field" id="_meta_field" class="widefat">
    <option value="Option 1" <?php selected( $metaField, 'Option 1' ); ?>>Option 1</option>';
    <option value="Option 2" <?php selected( $metaField, 'Option 2' ); ?>>Option 2</option>';
    <option value="Option 3" <?php selected( $metaField, 'Option 3' ); ?>>Option 3</option>';
</select>
<?php
<?php
// outputs a form with radio buttons
echo '<p>This is a good place for helper text.</p>';
echo'<label for="_meta_field">Meta Field</label>';
?>
<form>
    <input style="margin: 5px 10px 5px 0;" type="radio" name="_meta_field" value="Option 1" <?php checked( $metaField, 'Option 1' ); ?> />Option 1<br />
    <input style="margin: 5px 10px 5px 0;" type="radio" name="_meta_field" value="Option 2" <?php checked( $metaField, 'Option 2' ); ?> />Option 2<br />
</form>
<?php
<?php
/**
 * Add a custom post type with custom meta fields
 */

// creates custom post type
function create__custom_post_type() {
    $labels = array(
        'name' => __( 'Custom_Post_Name' ),
        'singular_name' => __( 'Custom_Post_Name' ),
        'add_new' => __( 'New Custom_Post_Name' ),
        'add_new_item' => __( 'Add Custom_Post_Name' ),
        'edit_item' => __( 'Edit Custom_Post_Name' ),
        'new_item' => __( 'New Custom_Post_Name' ),
        'view_item' => __( 'View Custom_Post_Name' ),
        'search_items' => __( 'Search Custom_Post_Name' ),
        'not_found' =>  __( 'No Custom_Post_Name Found' ),
        'not_found_in_trash' => __( 'No Custom_Post_Name found in Trash' ),
    );
    $args = array(
        'labels' => $labels,
        'public' => true,  // sets a default for 'show_in_nav_menus', 'show_ui', 'exclude_from_search', and 'publicly_queryable'
        'hierarchical' => false,  // makes this post type a page (true) or a post (false)
        'exclude_from_search' => false,  // excludes this post type from front end search results (true)
        'publicly_queryable'  => true,  // makes the post type accessible by URL queries (true)
        'show_ui' => true,  // creates an admin menu (true)
        'show_in_menu' => true,  // creates a top level admin menu (true), a submenu item in another top level menu (e.g. 'tools.php', 'edit.php?post_type=page'), or no menu (false)
        'show_in_nav_menus' => true, // makes this post type available for use in the menu editor
        'menu_position' =>  6,  // sets post type admin menu position
        'menu_icon'   => 'dashicons-format-status',  // sets admin menu icon, can be dashicon or SVG ('data:image/svg+xml;base64,'.svgURL)
        'supports' => array(  // sets core features for post type
          'title',
          'custom-fields',
          'editor',
          'excerpt',
          'thumbnail',
          'revisions',
          'comments',
          'trackbacks',
          'author',
          // allows for templates and menu order, post type must be a page ('hierarchical' => true)
          // 'page-attributes',
        ),
        'register_meta_box_cb' => 'create__custom_post_type__meta', // sets callback function for custom meta fields
        'taxonomies' => array('issues', 'category'),  // sets available taxonomies for the post type
        'has_archive' => true  // creates archive page for post type (true)
    );
    register_post_type( 'custom_post_type', $args );
}
add_action( 'init', 'create__custom_post_type' );

// creates custom meta boxes
function create__custom_post_type__meta() {
    add_meta_box(
        'custom_post_type__meta_field',  // sets ID for the meta box attribute
        'Meta Field',  // Title of the meta box
        'custom_post_type__meta_field',  // sets callback function to echo the box output
        'custom_post_type',  // sets screens where the meta box will appear
        'side',  // positions the meta box on right column (side) or main column (normal)
        'high'  // positions the meta box at the top (high) or bottom (low) of its context
    );
}

// creates custom meta box output
function custom_post_type__meta_field() {
    global $post;  // set $post to the current post ID
    $originalpost = $post;  // stores the current $post so it can be reset after a wp_query()
    wp_nonce_field( basename( __FILE__ ), 'custom_post_type__meta_nonce' );  // sets nonce to be checked when saving meta
    $metaField = get_post_meta( $post->ID, '_meta_field', true );  // gets the meta data if it already exists
    
    // outputs a simple text field
    echo '<p>This is a good place for helper text.</p>';
    echo'<label for="_meta_field">Meta Field</label>';
    echo '<input type="_meta_field" name="_meta_field" id="_meta_field" value="' . esc_textarea( $metaField )  . '" class="widefat">';
}

// saves custom meta box data
function save__custom_post_type__meta( $post_id, $post ) {
    // return if the user doesn't have edit permissions.
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return $post_id;
    }
    // return unless nonce is verified
    if ( ! isset( $_POST['custom_post_type__meta_nonce'] ) || ! wp_verify_nonce( $_POST['custom_post_type__meta_nonce'], basename(__FILE__) ) ) {
        return $post_id;
    }
    // sanitize the meta data save it into an array
    $meta_array['_meta_field'] = esc_textarea( $_POST['_meta_field'] );
    // $meta_array['_meta_field2'] = esc_textarea( $_POST['_meta_field2'] );

    foreach ( $meta_array as $key => $value ) :
        // avoid duplicate data during revisions
        if ( 'revision' === $post->post_type ) {
            return;
        }
        // update the meta value it if already has one
        if ( get_post_meta( $post_id, $key, false ) ) {
            update_post_meta( $post_id, $key, $value );
        // otherwise create meta entry with new value
        } else {
            add_post_meta( $post_id, $key, $value);
        }
        // delete meta entry if the field has no value
        if ( ! $value ) {
            delete_post_meta( $post_id, $key );
        }
    endforeach;
}
add_action( 'save_post', 'save__custom_post_type__meta', 10, 2 );  // hook to 'save_post' action, $callback, priority (1-10:high-low), $callback args

以上是关于php 自定义元字段的自定义帖子类型的主要内容,如果未能解决你的问题,请参考以下文章

php 通过acf选择字段查询类别中的自定义帖子类型

PHP wordpress自定义帖子类型元框和字段

通过存档页面上的自定义字段查询自定义帖子类型

通过自定义帖子类型中的字段分配模板的过滤器或操作挂钩

带有元框字段的自定义文章类型

php 具有自定义分类类别的自定义帖子类型