提问人:stst 提问时间:8/5/2023 更新时间:8/7/2023 访问量:62
Woocommerce - 生成父类别和子类别的嵌套 ul 层次结构
Woocommerce - generate nested ul hierarchy of parent categories and subcategories
问:
我正在尝试创建一个嵌套的 ul/li 层次结构,其中包含用于加载子类别产品的链接。子类别链接应嵌套在父类别(如果有)中,单击父类别 li 元素不会加载属于该父类别的子类别的所有产品,但单击父类别 li 元素会展开/折叠嵌套的 ul 中的子类别,单击其中的子类别链接将加载所选子类别链接的产品。
以下是我目前所取得的成就:
我至少成功获得了所有类别,包括父类别和子类别,然后单击链接会加载相应的产品。所以链接可以工作,但我不知道如何成功构建嵌套在其父类别中的子类别链接的层次结构。
function loadProductCategoriesAndGenerateLinks() {
// Show the loading spinner
$("#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();
// Recursive function to generate the category tree
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) {
// If the category has children, recursively generate their tree
generateCategoryTree(category.children, li);
}
ul.append(li);
});
parentElement.append(ul); // Append the generated <ul> with <li> elements to the parent <li>
}
// Start generating the category tree from the top-level categories
generateCategoryTree(categories, treeContainer);
// Hide the loading spinner after the category tree is generated
$("#loading-spinner2").hide();
}
},
error: function(error) {
// Handle error if necessary
// Hide the loading spinner in case of an error
$("#loading-spinner2").hide();
}
});
}
当然,我现在得到的是这样的:
<ul>
<li><a>Link to Subcategory 1</a></li>
<li><a>Link to Subcategory 2</a></li>
<li><a>Link to Subcategory 3</a></li>
<li><a>Link to Subcategory 4</a></li>
<li><a>Link to Parent category 1 (for example of Subcategory 3 and 4)</a></li>
<li><a>Link to Subcategory 5</a></li>
</ul>
问题是我不知道这些类别的父子关系是如何在woocommerce中解决的。我将不胜感激任何帮助!
答:
0赞
stst
8/7/2023
#1
所以我已经实现了我需要的东西,一个通用的 aproach。我连接到数据库并从表中获取数据以生成 ul:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Get the correct path to the db-config.php file, don'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( 'config/db-config.php' );
// 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("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 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 = "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 加载。
评论
0赞
stst
8/7/2023
顺便说一句:这也适用于所需的更多更深层次(sub-sub-sub-....类别)
评论