为WordPress文章页面添加自定义字段

前言

还好 WordPress 功能非常强大,可通过代码或者 SQL 自动为所有文章添加自定义字段。

参数说明

  • $id:字段id,唯一
  • $title:标题名称
  • $callback:回调函数
  • $post_type:文章类型
  • $context:显示位置
  • $priority:优先级

新建一个分类页面并添加新字段

<?php
// 新建分类页面
function tutorialshares_taxonomy_add_new_meta_field() {
	// 自定义元字段添加到添加分类页面
	?>
	<div class="form-field">
		<label for="term_meta[custom_term_meta]"><?php _e( 'Example meta field', 'tutorialshares' ); ?></label>
		<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="">
		<p class="description"><?php _e( 'Enter a value for this field','tutorialshares' ); ?></p>
	</div>
<?php
}
add_action( 'category_add_form_fields', 'tutorialshares_taxonomy_add_new_meta_field', 10, 2 );
你可以试着配置第一个参数TAYNOMY_NAME,_ADD_FORM_FILES,以设置要将字段添加到的分类。
在以上示例中,将使用类别分类。

 

编辑分类页添加字段

<?php
// 编辑页面
function tutorialshares_taxonomy_edit_meta_field($term) {
 
	// ID放入变量中
	$t_id = $term->term_id;
 
	// 检索此元字段的现有值。会返回一个数组
	$term_meta = get_option( "taxonomy_$t_id" ); ?>
	<tr class="form-field">
	<th scope="row" valign="top"><label for="term_meta[custom_term_meta]"><?php _e( 'Example meta field', 'tutorialshares' ); ?></label></th>
		<td>
			<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="<?php echo esc_attr( $term_meta['custom_term_meta'] ) ? esc_attr( $term_meta['custom_term_meta'] ) : ''; ?>">
			<p class="description"><?php _e( 'Enter a value for this field','tutorialshares' ); ?></p>
		</td>
	</tr>
<?php
}
add_action( 'category_edit_form_fields', 'tutorialshares_taxonomy_edit_meta_field', 10, 2 );

 保存数据

// 保存额外的分类字段回调函数。
function save_taxonomy_custom_meta( $term_id ) {
	if ( isset( $_POST['term_meta'] ) ) {
		$t_id = $term_id;
		$term_meta = get_option( "taxonomy_$t_id" );
		$cat_keys = array_keys( $_POST['term_meta'] );
		foreach ( $cat_keys as $key ) {
			if ( isset ( $_POST['term_meta'][$key] ) ) {
				$term_meta[$key] = $_POST['term_meta'][$key];
			}
		}
		// Save the option array.
		update_option( "taxonomy_$t_id", $term_meta );
	}
}  
add_action( 'edited_category', 'save_taxonomy_custom_meta', 10, 2 );  
add_action( 'create_category', 'save_taxonomy_custom_meta', 10, 2 );

 

 调用

$metafieldArray = get_option('taxonomy_'. $term->term_id);
$metafieldoutput = $metafieldArray['custom_term_meta'];

echo $metafieldoutput;

 

 

 

版权声明:
作者:小和
链接:https://www.xhfun.cn/wordpress_addcustom.html
来源:小和Fun
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>
文章目录
关闭
目 录