亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Method 1: Tag related
Method 2: Classification related
Method three: Tag related, SQL acquisition
Method 4: Classification related, SQL Get
Method 5: Author related
Time efficiency comparison
Home CMS Tutorial WordPress How does WordPress implement related article functions? Several ways to share

How does WordPress implement related article functions? Several ways to share

Mar 01, 2023 pm 08:17 PM
php wordpress

How does WordPress implement the related article function? The following article will introduce to you several ways to implement related articles in WordPress code. I hope it will be helpful to you!

How does WordPress implement related article functions? Several ways to share

Many WordPress plug-ins can realize the functions of related articles. The advantage of plug-ins is that they are simple to configure, but they may have some small impact on the speed of the website, so many people still prefer I like to use code to implement the required functions, but then again, code implementation also has shortcomings, that is, the configuration is complicated, and people who don’t understand code are completely confused or can only copy other people’s code, so it is better to use plug-ins.

Here I have compiled several ways to use code to implement related articles. The functions of each part of the code will be detailed and how to customize the functions you want. I hope it will be useful to everyone. help. Before we start, let me explain that the HTML code format output by all the following methods is in the following form. You can modify it according to your needs:

<ul id="xxx">
    <li>* <a title="文章標題1" rel="bookmark" href="文章鏈接1">文章標題1</a></li>
    <li>* <a title="文章標題2" rel="bookmark" href="文章鏈接2">文章標題2</a></li>
    ......
</ul>

First get all the tags of the article, and then get n articles under these tags, then these n articles are articles related to the article. All WordPress related article plug-ins that can be seen now use this method. The following is the implemented code:

<ul id="tags_related">
<?php
global $post;
$post_tags = wp_get_post_tags($post->ID);
if ($post_tags) {
  foreach ($post_tags as $tag) {
    // 獲取標簽列表
    $tag_list[] .= $tag->term_id;
  }
  // 隨機獲取標簽列表中的一個標簽
  $post_tag = $tag_list[ mt_rand(0, count($tag_list) - 1) ];
  // 該方法使用 query_posts() 函數來調用相關文章,以下是參數列表
  $args = array(
        &#39;tag__in&#39; => array($post_tag),
        &#39;category__not_in&#39; => array(NULL),  // 不包括的分類ID
        &#39;post__not_in&#39; => array($post->ID),
        &#39;showposts&#39; => 6,            // 顯示相關文章數量
        &#39;caller_get_posts&#39; => 1
    );
  query_posts($args);
  if (have_posts()) {
    while (have_posts()) {
      the_post(); update_post_caches($posts); ?>
    <li>* <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
    }
  }
  else {
    echo &#39;<li>* 暫無相關文章</li>&#39;;
  }
  wp_reset_query(); 
}
else {
  echo &#39;<li>* 暫無相關文章</li>&#39;;
}
?>
</ul>

Instructions for use: "Category ID not included" refers to related articles that do not display articles under this category. Just change the NULL in the peer to the ID of the article category. More The IDs are separated by half-width commas. Because only 6 related articles are displayed here, no matter how many values ????are assigned to the parameter tag__in of query_posts(), only 6 articles under one tag will be displayed, unless the first tag has 1 article and the second tag has 2 articles, and the third one has 3 articles. . . . . . So if this article has multiple tags, then what we do is to randomly get the id of a tag, assign it to the tag__in parameter, and get the 6 articles under that tag.

This method achieves the purpose of obtaining related articles by obtaining the classification id of the article, and then obtaining the articles under this category.

<ul id="cat_related"><?phpglobal $post;$cats = wp_get_post_categories($post->ID);if ($cats) {
    $args = array(
		  &#39;category__in&#39; => array( $cats[0] ),
		  &#39;post__not_in&#39; => array( $post->ID ),
		  &#39;showposts&#39; => 6,
		  &#39;caller_get_posts&#39; => 1
	  );
  query_posts($args);

  if (have_posts()) {
    while (have_posts()) {
      the_post(); update_post_caches($posts); ?>
  <li>* <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li><?php
    }
  } 
  else {
    echo &#39;<li>* 暫無相關文章</li>&#39;;
  }
  wp_reset_query(); }else {
  echo &#39;<li>* 暫無相關文章</li>&#39;;}?></ul>

The principle of obtaining related articles is similar to method one, but when obtaining articles, Use SQL statements to directly read the database, thereby randomly obtaining 6 related article records, instead of the WordPress function query_posts().

<ul id="tags_related"><?phpglobal $post, $wpdb;$post_tags = wp_get_post_tags($post->ID);if ($post_tags) {
    $tag_list = &#39;&#39;;
    foreach ($post_tags as $tag) {
        // 獲取標簽列表
        $tag_list .= $tag->term_id.&#39;,&#39;;
    }
    $tag_list = substr($tag_list, 0, strlen($tag_list)-1);

    $related_posts = $wpdb->get_results("
        SELECT DISTINCT ID, post_title
        FROM {$wpdb->prefix}posts, {$wpdb->prefix}term_relationships, {$wpdb->prefix}term_taxonomy
        WHERE {$wpdb->prefix}term_taxonomy.term_taxonomy_id = {$wpdb->prefix}term_relationships.term_taxonomy_id
        AND ID = object_id
        AND taxonomy = &#39;post_tag&#39;
        AND post_status = &#39;publish&#39;
        AND post_type = &#39;post&#39;
        AND term_id IN (" . $tag_list . ")
        AND ID != &#39;" . $post->ID . "&#39;
        ORDER BY RAND()
        LIMIT 6");
        // 以上代碼中的 6 為限制只獲取6篇相關文章
        // 通過修改數字 6,可修改你想要的文章數量

    if ( $related_posts ) {
        foreach ($related_posts as $related_post) {?>
    <li><a href="<?php echo get_permalink($related_post->ID); ?>" rel="bookmark" title="<?php echo $related_post->post_title; ?>"><?php echo $related_post->post_title; ?></a></li><?php   } 
    }
    else {
      echo &#39;<li>暫無相關文章</li>&#39;;
    } }else {
  echo &#39;<li>暫無相關文章</li>&#39;;}?></ul>

The principle of getting related articles is similar to method two, but when getting articles, SQL statements are used to directly read the database, thereby randomly obtaining 6 related article records, instead of using WordPress functions. query_posts().

<ul id="cat_related"><?phpglobal $post, $wpdb;$cats = wp_get_post_categories($post->ID);if ($cats) {
  $related = $wpdb->get_results("
  SELECT post_title, ID
  FROM {$wpdb->prefix}posts, {$wpdb->prefix}term_relationships, {$wpdb->prefix}term_taxonomy
  WHERE {$wpdb->prefix}posts.ID = {$wpdb->prefix}term_relationships.object_id
  AND {$wpdb->prefix}term_taxonomy.taxonomy = &#39;category&#39;
  AND {$wpdb->prefix}term_taxonomy.term_taxonomy_id = {$wpdb->prefix}term_relationships.term_taxonomy_id
  AND {$wpdb->prefix}posts.post_status = &#39;publish&#39;
  AND {$wpdb->prefix}posts.post_type = &#39;post&#39;
  AND {$wpdb->prefix}term_taxonomy.term_id = &#39;" . $cats[0] . "&#39;
  AND {$wpdb->prefix}posts.ID != &#39;" . $post->ID . "&#39;
  ORDER BY RAND( )
  LIMIT 6");

  if ( $related ) {
	  foreach ($related as $related_post) {?>
	<li>* <a href="<?php echo get_permalink($related_post->ID); ?>" rel="bookmark" title="<?php echo $related_post->post_title; ?>"><?php echo $related_post->post_title; ?></a></li><?php
    } 
  }
  else {
    echo &#39;<li>* 暫無相關文章</li>&#39;;
  } }else {
  echo &#39;<li>* 暫無相關文章</li>&#39;;}?></ul>

This method is to obtain other articles of the author of the article to serve as related articles, code As follows:

<ul id="author_related"><?php
  global $post;
  $post_author = get_the_author_meta( &#39;user_login&#39; );
  $args = array(
        &#39;author_name&#39; => $post_author,
        &#39;post__not_in&#39; => array($post->ID),
        &#39;showposts&#39; => 6,				// 顯示相關文章數量
        &#39;orderby&#39; => date,			// 按時間排序
        &#39;caller_get_posts&#39; => 1
    );
  query_posts($args);

  if (have_posts()) {
    while (have_posts()) {
      the_post(); update_post_caches($posts); ?>
  <li>* <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li><?php
    }
  }
  else { 
    echo &#39;<li>* 暫無相關文章</li>&#39;;
  }
  wp_reset_query();?></ul>

Time efficiency comparison

We measure the code execution time of each of the above related articles in order to evaluate the efficiency of each of the above methods. , provide reference for your choice. The following is to obtain 6 related articles in the same article. The final calculation time of each method above is as follows:

Method one: 0.18067908287048 seconds
Method two: 0.057158946990967 seconds
Method three: 0.037126064300537 seconds
Method 4: 0.045628070831299 seconds
Method 5: 0.023991823196411 seconds

Recommended study: "WordPress Tutorial"

The above is the detailed content of How does WordPress implement related article functions? Several ways to share. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution Jul 25, 2025 pm 07:06 PM

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.

See all articles