search
HomeBackend DevelopmentPHP TutorialGet the number of articles under a specified category and its subcategories in WordPress, the number of wordpress articles_PHP tutorial

Get the number of articles under a specified category and its subcategories in WordPress, the number of wordpress articles

Get the number of articles in a specific category

Sometimes we want to get the number of articles under a certain category so that it can be displayed somewhere on the blog. Here are several ways to get the number of articles in a specific category. You can choose according to your personal preferences:

Method 1:

Place the following PHP code in functions.php in the theme directory:

function wt_get_category_count($input = '') {
 global $wpdb;

 if($input == '') {
  $category = get_the_category();
  return $category[0]->category_count;
 }
 elseif(is_numeric($input)) {
  $SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->term_taxonomy.term_id=$input";
  return $wpdb->get_var($SQL);
 }
 else {
  $SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->terms.slug='$input'";
  return $wpdb->get_var($SQL);
 }
}

Then just call the function where needed. This function provides three calling methods:

1. Call this function in the main loop and provide no parameters, then return the number of articles in the first category:

<&#63;php echo wt_get_category_count(); &#63;>

2. The provided parameter is a number, and the number is the ID number of the category, then the number of articles in the category corresponding to the ID is returned:

<&#63;php echo wt_get_category_count(1); &#63;>

3. If the alias of the category is provided, the number of category articles corresponding to the abbreviation (alias) will be returned:

<&#63;php echo wt_get_category_count('hello-world'); &#63;>

This function will have a slight statistical error in the number of articles for categories containing subcategories. Statistics for cases where the number of classified articles is 0 are not very good either.

Method 2:

In fact, we can directly use WordPress’s built-in function wp_list_categories(), just pay attention when passing the function:

<&#63;php echo strip_tags(wp_list_categories('include=3&hide_empty=0&use_desc_for_title =0&echo=0&show_count=1&style=none&hierarchical =0&title_li=')); &#63;>

Change the 3 after the equal sign in the include parameter to the category ID you want to count the number of articles. The final output format is category name (number of articles)

Method 3:

Use WordPress built-in function get_category_by_slug()

<&#63;php
 // 将以下category-name改成你的分类别名即可
 echo get_category_by_slug('category-name')->count; 
&#63;>

Method 4:

Use WordPress built-in function get_category

<&#63;php
 // 将以下cat_ID改成你的分类ID即可
 echo get_category(cat_ID)->count; 
&#63;>

Summary:

Methods 1, 3, and 4 can obtain the pure number of articles. In terms of the amount of code, method 1 has the most code, and method 3 and 4 have the least code. In terms of execution efficiency, the execution time of method one is about 0.002 seconds, which is the most efficient; the execution time of the fourth method is about 0.004 seconds; the execution time of method three is the worst, and the execution time is about 0.008 seconds. The reason why there is such a big difference in execution efficiency is that method one focuses on one thing, which is to find the number of articles, and only performs a database query, while methods three and four are WordPress built-in functions, although they only require one line of code. But they are not specifically designed to query the number of classified articles, but to obtain all the information of the classification! In addition, these three methods will not count the number of articles under subcategories.

There is no distinction between any of the above methods that is better or worse. The few milliseconds difference in execution time cannot be felt at all. You can choose the relevant method according to your personal preferences.

Get the number of articles in the specified category and its subcategories

There may be times when we need to obtain the number of articles in a specified category and all its subcategories. Let’s take a look at the relevant implementation methods.
First, define the implementation function and copy the following php code into functions.php of the current theme:

function ludou_get_cat_postcount($id) {
 // 获取当前分类信息
 $cat = get_category($id);

 // 当前分类文章数
 $count = (int) $cat->count;

 // 获取当前分类所有子孙分类
 $tax_terms = get_terms('category', array('child_of' => $id));

 foreach ($tax_terms as $tax_term) {
  // 子孙分类文章数累加
  $count +=$tax_term->count;
 }
 return $count;
}

Usage examples

Okay, the function is defined. When using it, you only need to pass the classification id parameter to the ludou_get_cat_postcount function. The following is an example of use:

<&#63;php
 echo 'ID为123的分类及其子孙分类的文章数量为:' . ludou_get_cat_postcount(123);
&#63;>

Articles you may be interested in:

  • Usage of functions in WordPress to obtain article information and category links
  • Methods in WordPress to obtain article author and category information Organize

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1087271.htmlTechArticleGet the number of articles under a specified category and its subcategories in WordPress. Sometimes, the number of WordPress articles can be used to get the number of articles in a specific category. We want to get the number of articles under a certain category (category),...
Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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 Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),