生成Woocommerce – 父类别和子类别的嵌套ul层次结构

huangapple go评论61阅读模式
英文:

Woocommerce - generate nested ul hierarchy of parent categories and subcategories

问题

我正在尝试创建一个嵌套的ul/li层次结构,其中包含加载子类别产品的链接。子类别链接应嵌套在父类别中(如果有的话),单击父类别li元素不会加载属于该父类别的所有子类别的产品,而是单击父类别li元素会展开/折叠嵌套ul中的子类别,并单击其中的子类别链接将加载所选子类别链接的产品。

到目前为止,我已经取得了一些进展:

我成功地获取了所有类别,包括父类别和子类别,至少单击链接会加载相应的产品。所以链接是有效的,但是我不知道如何成功地构建子类别链接嵌套在它们的父类别中。

function loadProductCategoriesAndGenerateLinks() {
  // 显示加载中的旋转图标
  $("#loading-spinner2").show();

  $.ajax({
    url: twentytwentyone_ajax_object.ajax_url,
    type: 'POST',
    dataType: 'json',
    data: {
      action: 'get_product_categories',
    },
    success: function(response) {
      if (response && response.categories) {
        var categories = response.categories;
        var treeContainer = $("#category-tree");
        treeContainer.empty();

        // 递归函数生成类别树
        function generateCategoryTree(categories, parentElement) {
          var ul = $('<ul>');
          $.each(categories, function(index, category) {
            var li = $('<li>');
            var link = $('<a>')
              .addClass('load-category-products')
              .attr('href', '#')
              .attr('data-category', category.slug)
              .text(category.name);
            li.append(link);

            if (category.children && category.children.length > 0) {
              // 如果类别有子类别,递归生成它们的树
              generateCategoryTree(category.children, li);
            }

            ul.append(li);
          });

          parentElement.append(ul); // 将生成的<ul>与<li>元素附加到父<li>元素
        }

        // 从顶级类别开始生成类别树
        generateCategoryTree(categories, treeContainer);

        // 在生成类别树后隐藏加载中的旋转图标
        $("#loading-spinner2").hide();
      }
    },
    error: function(error) {
      // 处理错误(如果有必要)
      // 在错误情况下隐藏加载中的旋转图标
      $("#loading-spinner2").hide();
    }
  });
}

当然,目前我得到的结果看起来像这样:

<ul>
   <li><a>链接到子类别1</a></li>
   <li><a>链接到子类别2</a></li>
   <li><a>链接到子类别3</a></li>
   <li><a>链接到子类别4</a></li>
   <li><a>链接到父类别1(例如子类别3和4的示例)</a></li>
   <li><a>链接到子类别5</a></li>
</ul>

问题在于我不知道如何在WooCommerce中处理这些父子类别关系。如果能提供任何帮助,我将不胜感激!

英文:

I'm trying to create a nested ul/li hierarchy with links to load products of subcategories. the subcategory links shall be nested in the parent categories (if there are any), and clicking on the parent category li elements does not load all the products of the subcategories that belong to that parent category, but clicking on the parent category li elements expands/collapses the subcategories in the nested ul, and clicking on a subcategory link in there will load the products of the subcategory link that is selected.

Here's what I've achieved so far:

I'm successfully getting all categories including parent and subcategories at least, and clicking on the links loads the corresponding products. So the links work, but I don't know how to successfully build that hierarchy of subcategory links nested in their parent category.

function loadProductCategoriesAndGenerateLinks() {
// Show the loading spinner
$(&quot;#loading-spinner2&quot;).show();
$.ajax({
url: twentytwentyone_ajax_object.ajax_url,
type: &#39;POST&#39;,
dataType: &#39;json&#39;,
data: {
action: &#39;get_product_categories&#39;,
},
success: function(response) {
if (response &amp;&amp; response.categories) {
var categories = response.categories;
var treeContainer = $(&quot;#category-tree&quot;);
treeContainer.empty();
// Recursive function to generate the category tree
function generateCategoryTree(categories, parentElement) {
var ul = $(&#39;&lt;ul&gt;&#39;);
$.each(categories, function(index, category) {
var li = $(&#39;&lt;li&gt;&#39;);
var link = $(&#39;&lt;a&gt;&#39;)
.addClass(&#39;load-category-products&#39;)
.attr(&#39;href&#39;, &#39;#&#39;)
.attr(&#39;data-category&#39;, category.slug)
.text(category.name);
li.append(link);
if (category.children &amp;&amp; category.children.length &gt; 0) {
// If the category has children, recursively generate their tree
generateCategoryTree(category.children, li);
}
ul.append(li);
});
parentElement.append(ul); // Append the generated &lt;ul&gt; with &lt;li&gt; elements to the parent &lt;li&gt;
}
// Start generating the category tree from the top-level categories
generateCategoryTree(categories, treeContainer);
// Hide the loading spinner after the category tree is generated
$(&quot;#loading-spinner2&quot;).hide();
}
},
error: function(error) {
// Handle error if necessary
// Hide the loading spinner in case of an error
$(&quot;#loading-spinner2&quot;).hide();
}
});

}

Of course what I'm getting right now looks like this:

&lt;ul&gt;
&lt;li&gt;&lt;a&gt;Link to Subcategory 1&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a&gt;Link to Subcategory 2&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a&gt;Link to Subcategory 3&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a&gt;Link to Subcategory 4&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a&gt;Link to Parent category 1 (for example of Subcategory 3 and 4)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a&gt;Link to Subcategory 5&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

The problem is I don't know how these parent-child-relationships of categories are addressed in woocommerce. I would be very grateful for any help!

答案1

得分: 0

以下是翻译好的部分:

所以,我已经达到了我需要的目标,这是一种通用的方法。我连接到数据库并从表中获取数据以生成ul:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// 获取db-config.php文件的正确路径,请不要忘记使用一个包含DENY FROM ALL的.htaccess文件,理想情况下,您应该将db-config.php及其.htaccess文件放在项目根文件夹之外的某个位置
$db_config_path = get_theme_file_path( 'config/db-config.php' );

// 在尝试包含它之前检查db-config.php文件是否存在
if ( file_exists( $db_config_path ) ) {
    // 包含数据库配置文件
    require_once $db_config_path;

    // 创建数据库连接
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("Database connection failed: " . $e->getMessage());
    }
} else {
    die("Database configuration file not found.");
}

// 从数据库中获取嵌套分类并将其显示为带有链接的嵌套无序列表的函数
function fetchNestedCategories($parent_id = 0, $level = 0)
{
    global $pdo;
    $sql = "SELECT t.term_id, t.name, tt.parent, t.slug
        FROM wc_terms AS t
        LEFT JOIN wc_term_taxonomy AS tt ON t.term_id = tt.term_id
        WHERE tt.taxonomy = 'product_cat' AND tt.parent = :parent_id
        ORDER BY t.name";

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':parent_id', $parent_id, PDO::PARAM_INT);
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($categories) {
        echo '<ul class="some-ul-class">';
        foreach ($categories as $category) {
            echo '<li class="some-li-class"><a href="#" class="category" data-category="' . $category['slug'] . '">' . $category['name'] . '</a></li>';
            fetchNestedCategories($category['term_id'], $level + 1);
        }
        echo '</ul>';
    }
}

我得到的HTML输出很好,提供了我需要的一切。然后你只需在需要显示类别的位置显示它们:

<?php fetchNestedCategories(); ?>

我只是以此为基础通过JavaScript生成实际的类别链接,这样当您点击子类别链接时,将通过Ajax加载该子类别的产品。

英文:

So I've achieved what i needed, a generic aproach. I connect to the database and take the data from the tables to generate the ul:

&lt;?php
ini_set(&#39;display_errors&#39;, 1);
ini_set(&#39;display_startup_errors&#39;, 1);
error_reporting(E_ALL);
// Get the correct path to the db-config.php file, don&#39;t forget to use a .htaccess file containing DENY FROM ALL, ideally you should place the db-config.php and its .htaccess file somewhere outside of the root folder of your project
$db_config_path = get_theme_file_path( &#39;config/db-config.php&#39; );
// Check if the db-config.php file exists before attempting to include it
if ( file_exists( $db_config_path ) ) {
// Include the database configuration file
require_once $db_config_path;
// Create a database connection
try {
$pdo = new PDO(&quot;mysql:host=$host;dbname=$dbname&quot;, $username, $password);
$pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die(&quot;Database connection failed: &quot; . $e-&gt;getMessage());
}
} else {
die(&quot;Database configuration file not found.&quot;);
}
// Function to fetch nested categories from the database and display them as a nested unordered list with links
function fetchNestedCategories($parent_id = 0, $level = 0)
{
global $pdo;
$sql = &quot;SELECT t.term_id, t.name, tt.parent, t.slug
FROM wc_terms AS t
LEFT JOIN wc_term_taxonomy AS tt ON t.term_id = tt.term_id
WHERE tt.taxonomy = &#39;product_cat&#39; AND tt.parent = :parent_id
ORDER BY t.name&quot;;
$stmt = $pdo-&gt;prepare($sql);
$stmt-&gt;bindParam(&#39;:parent_id&#39;, $parent_id, PDO::PARAM_INT);
$stmt-&gt;execute();
$categories = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);
if ($categories) {
echo &#39;&lt;ul class=&quot;some-ul-class&quot;&gt;&#39;;
foreach ($categories as $category) {
echo &#39;&lt;li class=&quot;some-li-class&quot;&gt;&lt;a href=&quot;#&quot; class=&quot;category&quot; data-category=&quot;&#39; . $category[&#39;slug&#39;] . &#39;&quot;&gt;&#39; . $category[&#39;name&#39;] . &#39;&lt;/a&gt;&lt;/li&gt;&#39;;
fetchNestedCategories($category[&#39;term_id&#39;], $level + 1);
}
echo &#39;&lt;/ul&gt;&#39;;
}
}

the HTML output I'm getting is just fine and provides everything i need. Then you just show the categories wherever you want them to show:

&lt;?php fetchNestedCategories(); ?&gt;

I just take that as the basis to generate the actual links to the categories via javascript, so that when you click on a subcategory link, the products of that subcategory are loaded via ajax.

huangapple
  • 本文由 发表于 2023年8月5日 02:27:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定