You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取并展示嵌套数组中所有文章分类的slug?

Hey Paulette, let's fix this issue where you're only getting the first category slug for each post. The main problem is how you're accessing the category array and how you're trying to append the categories later—let's break this down and rewrite the relevant parts of your code.

What's Going Wrong

  1. Accessing only the first category: When you do const post_category = arr[5].slug, arr[5] is the entire category array of the post, so .slug just grabs the first element's slug. You need to iterate over the entire category array to get all slugs.
  2. Incorrect selector and timing: Your later loop tries to append categories using $(".category__list .italic .plus"), but this selector targets all elements with those classes globally. Plus, you're appending after adding the items to the DOM, which can lead to mismatched categories or duplicate content.

Fixed Code

Let's rewrite the $.each block to generate each post's category list inline, and use direct property access instead of relying on arr (which is error-prone):

$('#project-loader').on('click', function () {
  let pull_page = 1;
  let jsonFlag = true;
  if (jsonFlag) {
    jsonFlag = false;
    pull_page++;
    $.getJSON("/bklt-wp/wp-json/projets/all-projects?page=" + pull_page, function (data) {
      if (data.length) {
        var items = [];
        $.each(data, function (key, val) {
          // Use direct property access for clarity
          const post_title = val.title;
          const post_link = val.link;
          const post_thumbnail = val.thumbnail;
          const post_categories = val.category;

          // Generate the category list items
          let categoryItems = '';
          if (post_categories.length > 0) {
            categoryItems = post_categories.map(cat => `<li class="category__item">${cat.slug}</li>`).join('');
          }

          // Build the item string with the embedded category list
          let item_string = `
            <li class="project__item">
              <a href="${post_link}" class="project__link" data-project="${post_categories.map(cat => cat.slug).join(',')}">
                ${post_title}&nbsp;
                <div class="project__italic">
                  (<ul class="category__list italic plus">${categoryItems}</ul>)
                </div>
              </a>
              <img src="${post_thumbnail}" class="project__img">
            </li>
          `;
          items.push(item_string);
        });

        // Append all items at once
        $(".project__list").append(items);

        // Handle loader and no posts logic
        if (data.length < 25) {
          $('#project-loader').hide();
          $('#ajax-no-posts').fadeIn();
        } else {
          $('li.loader').fadeOut();
        }
      } else {
        $('#project-loader').hide();
        $('#ajax-no-posts').fadeIn();
      }
    }).done(function (data) {
      if (data.length) {
        jsonFlag = true;
      }
    });
  }
});

Key Changes Explained

  • Direct property access: Instead of using arr[2], arr[3], etc., we use val.title, val.link—this makes the code way more readable and less likely to break if the JSON structure changes.
  • Generate categories inline: We map over the post_categories array to create each category list item, then embed that directly into the item_string. This ensures each post gets its own correct categories right when we build the HTML.
  • Fixed data-project attribute: Now it uses post_categories.map(cat => cat.slug).join(',') to include all slugs as a comma-separated string, instead of just the first one.
  • Removed the extra loop: We don't need the separate loop to append categories anymore—everything is handled when building each post's HTML, which avoids selector issues.

内容的提问来源于stack exchange,提问作者Paulette

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:37:44