php 如何在WooCommerce产品子类别中显示特定内容

i7uaboj4  于 2024-01-05  发布在  PHP
关注(0)|答案(2)|浏览(194)

我使用的代码需要在不同的类别页面上显示特定的内容。
我的类别具有以下结构:

    • 短裤
      • 带口袋的短裤

但是下面的代码只显示父类别(Man)和第一级子类别(Cloth)上的内容:

  1. add_action( 'woocommerce_archive_description', 'add_slide_text',1 );
  2. function add_slide_text() {
  3. $cat = get_queried_object();
  4. if ( is_product_category() ) {
  5. if ( is_product_category( 'man' ) || $cat->parent === 233 ) {
  6. echo 'Hello man';
  7. } elseif ( is_product_category( 'woman' ) || $cat->parent === 232 ) {
  8. echo 'Hello woman';
  9. } else {
  10. echo '';
  11. }
  12. }
  13. }

字符串
如何强制它显示较低级别的子类别内容?例如,在“短裤”和“带口袋的短裤”(可能更低) 中?
任何帮助都很感激。

5vf7fwbs

5vf7fwbs1#

您可以使用get_term_children() WordPress function与WooCommerce产品类别自定义分类,以显示每个特定产品类别的特定文本“男人”和“女人”术语及其子女如下:

  1. add_action( 'woocommerce_archive_description', 'add_slide_text', 1 );
  2. function add_slide_text() {
  3. // Targeting WooCommerce product category archives
  4. if ( is_product_category() ) {
  5. $current_term = get_queried_object();
  6. $taxonomy = $current_term->taxonomy;
  7. // For "man" term (and term ID 233)
  8. $term_man_id = get_term_by('slug', 'man', $taxonomy)->term_id; // Get "man" term ID
  9. $children_man_ids = (array) get_term_children($term_man_id, $taxonomy); // Get children terms IDs
  10. $man_terms_ids = array_merge( array(233, $term_man_id), $children_man_ids ); // Merge terms IDs in a unique array
  11. // For "woman" term (and term ID 232)
  12. $term_woman_id = get_term_by('slug', 'woman', $taxonomy)->term_id; // Get "woman" term ID
  13. $children_woman_ids = (array) get_term_children($term_woman_id, $taxonomy); // Get children terms IDs
  14. $woman_terms_ids = array_merge( array(232, $term_woman_id), $children_woman_ids ); // Merge terms IDs in a unique array
  15. // Conditional text display
  16. if ( in_array( $current_term->term_id, $man_terms_ids ) ) {
  17. _e('Hello man', 'woocommerce');
  18. }
  19. elseif ( in_array( $current_term->term_id, $woman_terms_ids ) ) {
  20. _e('Hello woman', 'woocommerce');
  21. }
  22. }
  23. }

字符串
代码放在你的子主题的functions.php文件中(或插件中)。测试和工作。

展开查看全部
pieyvz9o

pieyvz9o2#

您可以使用WordPress函数cat_is_ancestor_of()
查看文档:https://developer.wordpress.org/reference/functions/cat_is_ancestor_of/
基本上,你给它给予两样东西:你认为是父类别和你期望是子类别的东西。
无论层次结构有多深,它都将返回true。
这里有一个快速的例子,你可以让它工作:

  1. $current_category = get_queried_object();
  2. $man_category_id = get_cat_ID('Man');
  3. // Check if the current category or its ancestors include the "Man" category
  4. if (cat_is_ancestor_of($man_category_id, $current_category->term_id)) {
  5. echo "Display your content here";
  6. }

字符串
只是提醒一下,我还没有测试过这段代码,所以请随意调整它以适应您的情况。

展开查看全部

相关问题