最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to Link to category titles if it is in the single post content?

programmeradmin3浏览0评论

My English is not good. sorry.

I want to link to titles of child-categories that are in the single post content. (Wordpress)

Example:

My Categories:

Aplle , Asia , Europ , North america , ...

My Post Content:

An apple is a sweet, edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus. The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found today. Apples have been grown for thousands of years in Asia and Europe and were brought to North America by European colonists. Apples have religious and mythological significance in many cultures, including Norse, Greek and European Christian tradition.

and, My troubled PHP script for automatic create Link to category titles if it is in the single post content:

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

UPDATE:

This code is work for last child-category and dont work for all child-categories of cat-id=1209:

<?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() ?>
发布评论

评论列表(0)

  1. 暂无评论