简体   繁体   中英

Wordpress Custom Post Type - Custom Fields

I am creating a custom theme and have added a few custom post types to it. For each custom post type I need to choose a specific set of custom fields each time I am making a new post in either section.

For example, I have the custom post type "Motors" for displaying the details of cars. Each time I add a new car using this custom post type I have to manually select the same set of custom fields and fill them in (Mileage, Fuel Type, Colour etc).

Is it possible to create a custom meta box for my Motors custom post type that uses the Wordpress custom fields? And can I have it automatically list out the 5 or so custom fields I always choose and simply require me to input a value for each before publishing?

Yes, it is possible. I would recommend using the Advanced Custom Fields plugin.

https://www.advancedcustomfields.com/

This is essentially what WordPress custom fields should be. It lets you add any number of custom fields, including text, textareas, images, etc. to specific post types, page types, etc. and would be ideal for what you are describing.

Try this below code. It will add a text box which allows to enter a image url that will display in the post. Use this below code and change your post type accordingly. Also you can any number of fields you want.

add_action('admin_init','add_metabox_post_banner_image_widget');
add_action('save_post','save_metabox_post_banner_image_widget');

/*
* Funtion to add a meta box to enable banner image widget on posts.
*/
function add_metabox_post_banner_image_widget()
{
  add_meta_box("banner_image", "Enable Banner Image", "enable_post_banner_image_widget", "post", "normal", "high"); /* replace "post" with your custom post value(eg: "motors") */
}

function enable_post_banner_image_widget(){
 global $post;

 $image=get_post_custom($post->ID );
//print_r($image);

 $banner_image_src = $image['post_banner_image_src'][0];

?>

<label for="post_banner_image_src">Banner Image Url:</label>
<input type="text" name="post_banner_image_src" id="post_banner_image_src" value="<?php if($banner_image_src!=''){echo $banner_image_src; } ?>" >
<p><em>Example: https://website.com/wp-content/uploads/2016/06/google.jpg</em></p>

<?php
}

/*
* Save the meta box value of banner image widget on posts.
*/
function save_metabox_post_banner_image_widget($post_id)
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;

$banner_image_src = isset($_POST['post_banner_image_src']) ? $_POST['post_banner_image_src']:'';

update_post_meta( $post_id, 'post_banner_image_src', $banner_image_src );

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM