Php 如果类别标题在单个帖子内容中,如何链接到类别标题?
我的英语不好。对不起 我想链接到单篇文章内容中的子类别标题 例如: 我的类别:Php 如果类别标题在单个帖子内容中,如何链接到类别标题?,php,wordpress,Php,Wordpress,我的英语不好。对不起 我想链接到单篇文章内容中的子类别标题 例如: 我的类别: <?php function link_words($content){ $term_id = 1209; $taxonomy_name = 'category'; $termchildren = get_term_children( $term_id, $taxonomy_name ); foreach ( $termchildren as $child ) { $
<?php
function link_words($content){
$term_id = 1209;
$taxonomy_name = 'category';
$termchildren = get_term_children( $term_id, $taxonomy_name );
foreach ( $termchildren as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
$termlink = get_term_link( $child, $taxonomy_name );
$mycatname = "$term->name";
$mycatlink = "<a href=$termlink> $term->name </a>";
$content = str_replace(array($mycatname), array($mycatlink) ,$content);
return $content;}
}
add_filter('the_content', 'link_words');
?>
<?php the_content() ?>
亚太、亚洲、欧洲、北美
我的帖子内容:
苹果是一种甜的、可食用的水果,由一棵树(苹果树)生产。树木在世界范围内种植,是苹果属中生长最广泛的物种。这种树起源于中部,它的野生祖先西弗西海棠(Malus sieversii)至今仍在那里被发现。苹果在欧洲已经种植了数千年,并且是由欧洲殖民者带来的。苹果在许多文化中都具有宗教和神话意义,包括挪威、希腊和欧洲基督教传统
此外,我的PHP脚本用于自动创建类别标题的链接(如果在单个帖子内容中):
<?php
$term_id = 1209;
$taxonomy_name = 'category';
$termchildren = get_term_children( $term_id, $taxonomy_name );
foreach ( $termchildren as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
$mycatone = "'" . $term->name . "',";
$mycattwo = '"' . "<a href='This-Category-URL-LINK'>" . $termd->name . "</a>" . '",';
}
function link_words($content){
$words = array( $mycatone );
$links = array( $mycattwo );
$content = str_replace($words , $links ,$content);
return $content;
}
add_filter('the_content', 'link_words');
?>
<?php the_content() ?>
更新:
此代码适用于最后一个儿童类别,不适用于所有儿童类别:
<?php
function link_words($content){
$term_id = 1209;
$taxonomy_name = 'category';
$termchildren = get_term_children( $term_id, $taxonomy_name );
foreach ( $termchildren as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
$termlink = get_term_link( $child, $taxonomy_name );
$mycatname = "$term->name";
$mycatlink = "<a href=$termlink> $term->name </a>";
$content = str_replace(array($mycatname), array($mycatlink) ,$content);
return $content;}
}
add_filter('the_content', 'link_words');
?>
<?php the_content() ?>
修复了我的问题:
<?php
function link_words( $text ) {
$replace = array();
$cats = get_categories('orderby=name&hide_empty=0');
if ( $cats ) {
foreach ( $cats as $cat ) {
$replace[ $cat->name ] = sprintf( '<a href=%s> %s </a>', esc_url( get_term_link($cat) ), esc_html($cat->name) );
}
}
$text = str_replace( array_keys($replace), $replace, $text );
return $text;
}
add_filter( 'the_content', 'link_words' );
?>
<?php the_content() ?>
资料来源:
我想我的数组错了