有时候需要给文章添加一些自定义字段,比如、价格和尺寸等自定义字段,参考如下代码。
/** * 文章编辑页-添加自定义字段 */ add_action('add_meta_boxes', 'flame_add_custom_box'); function flame_add_custom_box() { //需要添加自定义字段的文章类型 array('post','page','audio'); $screens = array('audios'); foreach ($screens as $screen) { add_meta_box( 'html_meta_div_id', __('主题自定义字段', 'field_textdomain'), 'flame_inner_custom_box', $screen ); } } /** * 显示自定义字段编辑框 */ function flame_inner_custom_box($post) { // 使用随机数进行核查 wp_nonce_field(plugin_basename(__FILE__), 'myplugin_noncename'); // 使用 get_post_meta 从数据库中检索现有的值,并应用到表单中 $oss_url = get_post_meta($post->ID, 'oss_url', true); $rt_author = get_post_meta($post->ID, 'rt_author', true); $price = get_post_meta($post->ID, 'price', true); echo ' <div class="rt-post-row"> <label for="rt_author">音频作者:</label> <input type="text" class="form-control" name="rt_author" value="' . esc_attr($rt_author) . '"> </div> <div class="rt-post-row"> <label for="price">价格:</label> <input type="text" class="form-control" name="price" value="' . esc_attr($price) . '" placeholder="单位是分"> </div> '; } /** * 文章保存时,保存自定义数据 */ add_action('save_post', 'flame_save_postdata'); function flame_save_postdata($post_id) { // 首先,我们需要检查当前用户是否被授权做这个动作。 if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) return; } else { if (!current_user_can('edit_post', $post_id)) return; } // 其次,我们需要检查,是否用户想改变这个值。 if (!isset($_POST['myplugin_noncename']) || !wp_verify_nonce($_POST['myplugin_noncename'], plugin_basename(__FILE__))) return; // 第三,我们可以保存值到数据库中 //如果保存在自定义的表,获取文章ID $post_ID = $_POST['post_ID']; // 作者 $rt_author = sanitize_text_field($_POST['rt_author']); add_post_meta($post_ID, 'rt_author', $rt_author, true) or update_post_meta($post_ID, 'rt_author', $rt_author); // 价格 $price = intval(sanitize_text_field($_POST['price']) ); add_post_meta($post_ID, 'price', $price, true) or update_post_meta($post_ID, 'price', $price); }
声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏