通知:
每天更新WordPress知识,建站故障请咨询技术客服QQ:1339586417

WordPress为文章目录添加自定义字段

本代码演示,如何给分类目录添加新字段,并且调用

新建分类页面,添加新字段

<?php
// Add term page
function tutorialshares_taxonomy_add_new_meta_field() {
	// this will add the custom meta field to the add new term page
	?>
	<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 );

您可以调整第一个参数{taxonomy_name}_add_form_fields以设置将字段添加到的分类法。在我的示例中,我将使用“类别”分类法。

编辑分类页面添加字段

<?php
// Edit term page
function tutorialshares_taxonomy_edit_meta_field($term) {
 
	// put the term ID into a variable
	$t_id = $term->term_id;
 
	// retrieve the existing value(s) for this meta field. This returns an array
	$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 );

保存数据

// Save extra taxonomy fields callback function.
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;
声明

⚠️免责声明:本站的资源均来自于用户投稿,仅为资源共享、作个人学习使用,其版权均归原作者所有。

⚠️侵权声明:如有侵权请发送邮件至:xjbqb@foxmail.com 或 点击右侧 私信:“管理员”反馈,我们将尽快处理。

⚠️转载声明:若需转载,请保留原文链接并附出处,谢谢合作。

给TA打赏
共{{data.count}}人
人已打赏
基础教程

WordPress 限制用户上传文件大小

2023-11-29 13:29:41

基础教程

为WordPress开启webp和svg支持

2023-11-29 13:33:06

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
我是底线可爱胖!冲鸭~