php - 如果它在单个帖子内容中,如何链接到类别标题?
问题描述
我英文不太好。对不起。
我想链接到单个帖子内容中的子类别标题。
例子:
我的分类:
Aplle , 亚洲 , 欧洲 , 北美 , ...
我的帖子内容:
苹果是一种由苹果树(Malus domestica)生产的甜味、可食用的水果。苹果树在世界范围内种植,是苹果属中种植最广泛的树种。这棵树起源于中亚,它的野生祖先,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() ?>
推荐阅读
- python - perl 中 useragent 和 http 库的 Python3 等效项是什么?
- asp.net-core-2.0 - NSwag 如何在 ASP.Net Zero 框架中工作?
- c# - 嗅探串口 - .net
- flutter - 如何删除 ReorderableListView 底部的额外间距 - 颤动?
- python - 如何每次运行只抓取更新的部分
- jquery - jQuery 在 991px 下调整大小时改变了一个函数
- python-3.x - multiprocessing.Manager().dict() 无法更新二级值
- php - 我正在尝试使用 php 发送邮件,但单击发送按钮后页面为空白且没有错误..我不知道为什么
- c++ - 访问不同的会话 tty
- ruby - 使用 || 为变量赋值 Ruby中带有if条件的运算符