我正在尝试创建一个嵌套的 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 中是如何处理的。我将非常感谢任何帮助!
所以我已经实现了我所需要的,一种通用方法。我连接到数据库并从表中获取数据来生成 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="ontology2255-ul">';
foreach ($categories as $category) {
echo '<li class="ontology2255-li"><a href="#" class="category2255" data-category="' . $category['slug'] . '">' . $category['name'] . '</a></li>';
fetchNestedCategories($category['term_id'], $level + 1);
}
echo '</ul>';
}
}
我得到的 HTML 输出很好,提供了我需要的一切。然后,您只需在想要显示的位置获取类别即可:
<?php fetchNestedCategories(); ?>
我只是以此为基础,通过javascript生成类别的实际链接,这样当您单击子类别链接时,该子类别的产品就会通过ajax加载。