search
HomeCMS TutorialWordPressSeparate lists for displaying WooCommerce categories, subcategories, and products

用于显示 WooCommerce 类别、子类别和产品的单独列表

WooCommerce gives you some options regarding what you can display on your archive pages:

  • product
  • Category (on main store page) or subcategory (on category page)
  • Products and Categories

When I build a store, I usually choose the third option: Products and Categories/Subcategories. This means visitors to my store can select products directly from the homepage or refine their searches by clicking on product category profiles.

However, this approach has a drawback: it displays categories/subcategories together, with no separation between the two. This means that if your product image is a different size than the product image, the layout may look a little confusing. Even if your images are the same size, if a row in your archive page contains both categories and products, missing the category's "Add to Cart" button will make the row look untidy because not all elements will have the same dimensions.

In this tutorial, I will show you how to display categories in a separate list before displaying products.

To do this, we will follow four steps:

  1. Determine the code WooCommerce uses to output categories and subcategories on archive pages.
  2. Create a plugin for our code.
  3. Write a function that puts a category or subcategory before the product list.
  4. Set the output style.

But before you start, you need to install WooCommerce, add some products and set up product categories and subcategories.

What do you need

To continue, you need:

  • Development installation of WordPress
  • Code Editor
  • WooCommerce installed and activated
  • Products Added - I have imported the dummy product data that comes with WooCommerce; see this guide for details on how to do this
  • WooCommerce Compatible Theme Activated - I'm using Storefront

Before you begin: Default options

Let’s take a look at what WooCommerce provides us by default.

I started by adding some images to my product categories and subcategories, since the WooCommerce dummy data doesn't contain them. I simply used an image of one product from each category or subcategory, as shown in the screenshot:

用于显示 WooCommerce 类别、子类别和产品的单独列表

Now, let’s see how WooCommerce displays product categories and products on archive pages.

If you haven't opened the customizer yet, select the WooCommerce tab and click Product Catalog.

用于显示 WooCommerce 类别、子类别和产品的单独列表

Under Store Page Display , select Show Categories and Products , then under Category Display select Show Subcategories and Products Strong>.

用于显示 WooCommerce 类别、子类别和产品的单独列表

Click Publish to save your changes and visit your website's store page. Mine looks like this:

用于显示 WooCommerce 类别、子类别和产品的单独列表

Because I have four categories and a grid of three side-by-side images, the first two products will appear side-by-side with one of the categories.

I want to make my categories and subcategories more prominent and simply display them separately from the product list. So let's do this.

Identifies the code WooCommerce uses to output the categories and products in the archive

The first step is to determine how WooCommerce outputs categories and subcategories. So let’s dig into the WooCommerce source code to find the relevant functions.

The file used by WooCommerce to display archive pages is archive-product.php, located in the templates folder.

In that file you can find this code, which outputs categories and products:

<?php
    /**
     * woocommerce_before_shop_loop hook
     *
     * @hooked woocommerce_result_count - 20
     * @hooked woocommerce_catalog_ordering - 30
    */
    do_action( 'woocommerce_before_shop_loop' );
?>
 
<?php woocommerce_product_loop_start(); ?>
 
    <?php woocommerce_product_subcategories(); ?>
 
    <?php while ( have_posts() ) : the_post(); ?>
 
        <?php wc_get_template_part( 'content', 'product' ); ?>
 
    <?php endwhile; // end of the loop. ?>
 
<?php woocommerce_product_loop_end(); ?>

So there is a woocommerce_product_subcategories() function that outputs categories or subcategories before running a loop that outputs products.

This function is pluggable, which means we can override it in the theme. Unfortunately, this doesn't entirely work because WooCommerce has a built-in style for clearing items, which will appear at the beginning of the row shown by default.

因此,我们将关闭存档页面上类别和子类别的显示,以便仅显示产品。然后,我们将创建一个输出产品类别或子类别的新函数,并将其挂钩到 woocommerce_before_shop_loop 操作,确保我们使用高优先级,以便它在已经挂钩到该操作的函数之后触发。 p>

注意:由于 WooCommerce 向每个第三个产品列表添加了清除内容,因此我们无法使用 woocommerce_product_subcategories() 函数或其编辑版本来显示类别。这是因为即使我们使用此功能单独显示类别,它也会清除列出的第三、第六(等等)类别或产品。我们可以尝试覆盖它,但编写我们自己的函数更简单。

所以让我们创建一个插件来实现这一点。

创建插件

在您的wp-content/plugins目录中,创建一个新文件夹并为其指定一个唯一的名称。我将我的命名为tutsplus-separate-products-categories-in-archives。在其中创建一个新文件,同样具有唯一的名称。我使用相同的名称:tutsplus-separate-products-categories-in-archives.php

打开您的文件并向其中添加以下代码:

<?php
/**
* Plugin Name: Tutsplus display WooCommerce products and categories/subcategories separately in archive pages
* Plugin URI: https://code.tutsplus.com/tutorials/woocommerce-display-product-categories-subcategories-and-products-in-two-separate-lists--cms-25479
* Description: Display products and categories / subcategories as two separate lists in product archive pages
* Version: 1.0
* Author: Rachel McCollin
* Author URI: https://rachelmccollin.co.uk
*
*
*/

您可能想要编辑作者详细信息,因为这是您正在编写的插件。保存您的文件并通过 WordPress 管理员激活插件。

编写我们的函数

现在让我们编写函数。但在开始之前,请关闭管理屏幕上的类别列表。打开定制器,单击 WooCommerce 选项,然后单击产品目录。对于每个商店页面显示默认类别显示选项,选择显示产品。点击发布保存您的更改。

您的商店页面现在看起来像这样:

用于显示 WooCommerce 类别、子类别和产品的单独列表

在您的插件文件中,添加以下内容:

function tutsplus_product_subcategories( $args = array() ) {

}

add_action( 'woocommerce_before_shop_loop', 'tutsplus_product_subcategories', 50 );

现在,在函数中添加以下代码:

$parentid = get_queried_object_id();

$args = array(
    'parent' => $parentid
);

$terms = get_terms( 'product_cat', $args );

if ( $terms ) {
    echo '<ul class="product-cats">';

    foreach ( $terms as $term ) {
        echo '<li class="category">';                 
            woocommerce_subcategory_thumbnail( $term );
            echo '<h2>';
                echo '<a href="' .  esc_url( get_term_link( $term ) ) . '" class="' . $term->slug . '">';
                    echo $term->name;
                echo '</a>';
            echo '</h2>';
        echo '</li>';
    }

    echo '</ul>';
}

让我们看一下该函数的作用:

  • 它标识当前查询的对象并将其 ID 定义为 $parentid
  • 它使用 get_terms() 来识别以当前查询项作为其父项的术语。如果这是商店主页面,则会返回顶级类别;如果这是一个类别存档,它将返回子类别。
  • 然后,它会检查是否存在任何术语,然后打开 for every 循环和 ul 元素。
  • 对于每个术语,它都会创建一个 li 元素,然后使用 woocommerce_subcategory_thumbnail() 输出类别图像,后跟其存档链接中的类别名称。

现在保存您的文件并刷新主商店页面。我的看起来像这样:

用于显示 WooCommerce 类别、子类别和产品的单独列表

类别已显示,但需要一些样式。接下来我们就这样做。

设置类别列表的样式

为了添加样式,我们的插件中需要一个样式表,我们需要将其排队。

在您的插件文件夹中,创建一个名为 css 的文件夹,并在其中创建一个名为 style.css 的文件。

现在,在您的插件文件中,将其添加到您已创建的函数上方:

function tutsplus_product_cats_css() {
    /* register the stylesheet */
    wp_register_style( 'tutsplus_product_cats_css', plugins_url( 'css/style.css', __FILE__ ) );
    /* enqueue the stylesheet */
    wp_enqueue_style( 'tutsplus_product_cats_css' );
}

add_action( 'wp_enqueue_scripts', 'tutsplus_product_cats_css' );

这会正确地将您刚刚创建的样式表排入队列。

现在打开样式表并添加以下代码。 WooCommerce 使用移动优先样式,因此我们也将使用它。

ul.product-cats {
    margin-left: 0;
}

ul.product-cats li {
    list-style: none;
    margin-left: 0;
    margin-bottom: 4.236em;
    text-align: center;
    position: relative;
}

ul.product-cats li img {
    margin: 0 auto; 
}

@media screen and (min-width:768px) {

    ul.product-cats li {
        width: 29.4117647059%;
        float: left;
        margin-right: 5.8823529412%;
    }

    ul.product-cats li:nth-of-type(3) {
        margin-right: 0;
    }

}

我已从 WooCommerce 使用的样式中复制了准确​​的宽度和边距。

现在再次检查您的主商店页面。这是我的:

用于显示 WooCommerce 类别、子类别和产品的单独列表

这是服装类别存档:

用于显示 WooCommerce 类别、子类别和产品的单独列表

这是它在较小屏幕上的外观:

用于显示 WooCommerce 类别、子类别和产品的单独列表

摘要

产品类别是 WooCommerce 的一大功能,但它们的显示方式并不总是理想。在本教程中,您学习了如何创建一个插件,该插件可以与产品列表分开输出产品类别或子类别,然后设置类别列表的样式。

您可以使用此代码在页面其他位置(例如,产品下方)输出类别或子类别列表,方法是将函数挂钩到 WooCommerce 模板文件中的不同操作挂钩。

If you are currently running a store that you would like to expand, or you are looking for some other WooCommerce-related plugins to look into, feel free to check out what plugins are available on CodeCanyon.

CodeCanyon Best WooCommerce Plugins of 2021

CodeCanyon offers the most flexible and feature-rich WooCommerce WordPress plugin on the market and will add another dimension of functionality to your online store that your users are accustomed to.

Whether you need to implement custom fields and uploads, display multiple currencies, or offer memberships, the various WooCommerce plugins available on CodeCanyon can help you accomplish these tasks.

In addition to all the high-quality WooCommerce plugins available, there are thousands of other high-quality WordPress plugins on CodeCanyon that can help enhance your website. Browse through the extensive plugin library and you’ll find plugins for all types of plugins, including forum, media, and SEO plugins.

Take advantage of CodeCanyon’s vast library of high-quality WordPress plugins today!

用于显示 WooCommerce 类别、子类别和产品的单独列表

If you need some help choosing the right WooCommerce plugin for you, check out these other posts on Envato Tuts:

The above is the detailed content of Separate lists for displaying WooCommerce categories, subcategories, and products. For more information, please follow other related articles on the PHP Chinese website!

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
Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

How customizable is WordPress, really?How customizable is WordPress, really?May 11, 2025 am 12:11 AM

WordPress is very customized, providing a wide range of flexibility and customizability. 1) Through the theme and plug-in ecosystem, 2) use RESTAPI for front-end development, 3) In-depth code level modifications, users can achieve a highly personalized experience. However, customization requires mastering technologies such as PHP, JavaScript, CSS, etc., and pay attention to performance optimization and plug-in selection to avoid potential problems.

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor