您不能为每个帖子创建主标记。标签是一种非海生分类法,根据定义,非海生分类法没有海生分类法,没有一个术语比其他术语更重要。
为了完成您的任务,大多数WP开发人员会建议您创建一些自定义字段来存储您的“主标签”,然后使用它来检索您的相关帖子。在你的函数中是这样的。php将构建自定义字段元盒:
/**
* Generated by the WordPress Meta Box Generator at http://goo.gl/8nwllb
*/
class Custom_Meta_Box {
private $screens = array(
\'post\',
);
private $fields = array(
array(
\'id\' => \'main-tag\',
\'label\' => \'Main tag\',
\'type\' => \'text\',
),
);
/**
* Class construct method. Adds actions to their respective WordPress hooks.
*/
public function __construct() {
add_action( \'add_meta_boxes\', array( $this, \'add_meta_boxes\' ) );
add_action( \'save_post\', array( $this, \'save_post\' ) );
}
/**
* Hooks into WordPress\' add_meta_boxes function.
* Goes through screens (post types) and adds the meta box.
*/
public function add_meta_boxes() {
foreach ( $this->screens as $screen ) {
add_meta_box(
\'main-tag\',
__( \'Main Tag\', \'your-textdomain\' ),
array( $this, \'add_meta_box_callback\' ),
$screen,
\'side\',
\'default\'
);
}
}
/**
* Generates the HTML for the meta box
*
* @param object $post WordPress post object
*/
public function add_meta_box_callback( $post ) {
wp_nonce_field( \'main_tag_data\', \'main_tag_nonce\' );
echo \'Use this field to set the main tag:\';
$this->generate_fields( $post );
}
/**
* Generates the field\'s HTML for the meta box.
*/
public function generate_fields( $post ) {
$output = \'\';
foreach ( $this->fields as $field ) {
$label = \'<label for="\' . $field[\'id\'] . \'">\' . $field[\'label\'] . \'</label>\';
$db_value = get_post_meta( $post->ID, \'main_tag\', true );
switch ( $field[\'type\'] ) {
default:
$input = sprintf(
\'<input id="%s" name="%s" type="%s" value="%s">\',
$field[\'id\'],
$field[\'id\'],
$field[\'type\'],
$db_value
);
}
$output .= \'<p>\' . $label . \'<br>\' . $input . \'</p>\';
}
echo $output;
}
/**
* Hooks into WordPress\' save_post function
*/
public function save_post( $post_id ) {
if ( ! isset( $_POST[\'main_tag_nonce\'] ) )
return $post_id;
$nonce = $_POST[\'main_tag_nonce\'];
if ( !wp_verify_nonce( $nonce, \'main_tag_data\' ) )
return $post_id;
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->fields as $field ) {
if ( isset( $_POST[ $field[\'id\'] ] ) ) {
switch ( $field[\'type\'] ) {
case \'email\':
$_POST[ $field[\'id\'] ] = sanitize_email( $_POST[ $field[\'id\'] ] );
break;
case \'text\':
$_POST[ $field[\'id\'] ] = sanitize_text_field( $_POST[ $field[\'id\'] ] );
break;
}
update_post_meta( $post_id, \'main_tag\', $_POST[ $field[\'id\'] ] );
} else if ( $field[\'type\'] === \'checkbox\' ) {
update_post_meta( $post_id, \'main_tag\', \'0\' );
}
}
}
}
new Custom_Meta_Box;
一旦有了自定义字段元盒,就应该用有效的标记slug(我建议slug优于名称或术语ID)填充它,并通过在single中进行此类查询来检索相关帖子。php:
$args = array(
\'meta_key\' => \'main_tag\',
\'meta_value\' => get_post_meta($post->ID, \'main_tag\', true);
);
$query = new WP_Query( $args );