如果它在单个帖子内容中,如何链接到类别标题?

我的英语不是很好。对不起。

我想链接到单个帖子内容中的子类别标题。

例子:

我的分类:

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() ?>


www说
浏览 131回答 1
1回答

红糖糍粑

修复了我的问题:<?phpfunction link_words( $text ) {&nbsp; &nbsp; $replace = array();&nbsp; &nbsp; $cats = get_categories('orderby=name&hide_empty=0');&nbsp; &nbsp; if ( $cats ) {&nbsp; &nbsp; &nbsp; &nbsp; foreach ( $cats as $cat ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $replace[ $cat->name ] = sprintf( '<a href=%s> %s </a>', esc_url( get_term_link($cat) ), esc_html($cat->name) );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; $text = str_replace( array_keys($replace), $replace, $text );&nbsp; &nbsp; return $text;}add_filter( 'the_content', 'link_words' );?><?php the_content() ?>
打开App,查看更多内容
随时随地看视频慕课网APP