首页 > 解决方案 > 如果它在单个帖子内容中,如何链接到类别标题?

问题描述

我英文不太好。对不起。

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

例子:

我的分类:

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

标签: phpwordpress

解决方案


修复了我的问题:

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

来源: Wordpress 用链接替换内容中的标记词


推荐阅读