我是 WordPress 的新手,想知道如何为 WordPress 中的类别设置自定义
<h1>
。目前:<h1>Category:Category name</h1>
。我花了半天时间才知道怎么做。文章中的建议不起作用。
插件:Yoast SEO、多合一 SEO 包、WP SEO Meta 在主题文件夹中编辑
functions.php
add_action("category_edit_form_fields", 'mayak_category_meta');
function mayak_category_meta( $term ) {
?>
<tr class="form-field">
<th scope="row" valign="top"><label>Заголовок (title)</label></th>
<td>
<input type="text" name="mayak[title]" value="<?php echo esc_attr( get_term_meta( $term->term_id, 'title', 1 ) ) ?>"><br />
<p class="description">Не более 60 знаков, включая пробелы</p>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label>Заголовок h1</label></th>
<td>
<input type="text" name="mayak[h1]" value="<?php echo esc_attr( get_term_meta( $term->term_id, 'h1', 1 ) ) ?>"><br />
<p class="description">Заголовок страницы</p>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label>Ключевые слова</label></th>
<td>
<input type="text" name="mayak[keywords]" value="<?php echo esc_attr( get_term_meta( $term->term_id, 'keywords', 1 ) ) ?>"><br />
<p class="description">Ключевые слова (keywords)</p>
</td>
</tr>
<?php
}
function mayak_save_meta( $term_id ) {
if ( ! isset($_POST['mayak']) )
return;
$mayak = array_map('trim', $_POST['mayak']);
foreach( $mayak as $key => $value ){
if( empty($value) ){
delete_term_meta( $term_id, $key );
continue;
}
update_term_meta( $term_id, $key, $value );
}
return $term_id;
}
add_action("create_category", 'mayak_save_meta');
add_action("edited_category", 'mayak_save_meta');
function mayak_filter_single_cat_title($term_name) {
$terms = get_category( get_query_var('cat'));
$cat_id = $terms->cat_ID;
$term_name = get_term_meta ($cat_id, 'title', true);
return $term_name;
}
add_filter('single_cat_title', 'mayak_filter_single_cat_title', 10, 1 );
function mayak_single_cat_title ($term_name){
if(empty($term_name)){
$terms = get_category( get_query_var( 'cat' ));
$cat_id = $terms->cat_ID;
$term_name = get_cat_name($cat_id);
}
return $term_name;
}
add_filter( 'single_cat_title', 'mayak_single_cat_title', 10, 1 );
function mayak_cat_caption($caption) {
$terms = get_category( get_query_var( 'cat' ));
$cat_id = $terms->cat_ID;
$caption = get_cat_name($cat_id);
echo $caption;
}
function mayak_cat_h1($name_cat) {
$terms = get_category( get_query_var( 'cat' ));
$cat_id = $terms->cat_ID;
$name_cat = get_term_meta ( $cat_id, 'h1', true );
echo $name_cat;
if(empty($name_cat)){
echo mayak_cat_caption($caption);
}
}
解决方案是编辑主题文件夹中的 archive.php 文件并添加以下代码:
<?php
$term = get_queried_object();
$term_h1 = get_field('h1', $term);
if ( empty( $term_h1 ) )
the_archive_title( '<h1 class="page-title">', '</h1>' );
else
echo '<h1 class="page-title">' . $term_h1 . '</h1>';
the_archive_description( '<div class="taxonomy-description">', '</div>' );
?>