繁体   English   中英

Wordpress自定义帖子类型 - 自定义字段

[英]Wordpress Custom Post Type - Custom Fields

我正在创建一个自定义主题,并为其添加了一些自定义帖子类型。 对于每个自定义帖子类型,每次我在任一部分中发布新帖子时,我都需要选择一组特定的自定义字段。

例如,我有自定义的帖子类型“Motors”用于显示汽车的详细信息。 每次我使用此自定义帖子类型添加新车时,我必须手动选择相同的自定义字段集并将其填入(里程,燃料类型,颜色等)。

是否可以为使用Wordpress自定义字段的我的Motors自定义帖子类型创建自定义元框? 我可以让它自动列出我总是选择的5个左右的自定义字段,并且只是要求我在发布前为每个字段输入一个值吗?

对的,这是可能的。 我建议使用高级自定义字段插件。

https://www.advancedcustomfields.com/

这基本上是WordPress自定义字段应该是什么。 它允许您向特定的帖子类型,页面类型等添加任意数量的自定义字段,包括文本,文本,图像等,并且非常适合您所描述的内容。

请尝试以下代码。 它将添加一个文本框,允许输入将在帖子中显示的图像URL。 使用以下代码并相应地更改您的帖子类型。 您也可以使用任意数量的字段。

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 );

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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