• Hi, I’m using LearnPress as a content manager in a headless UI application. I’m currently trying to filter courses based on categories using the LearnPress REST API. I have two category IDs: 66 and 67, and I’m using the following fetch function:

    const params = {
      ...(filter.search && { search: filter.search }),
      ...(filter.category && { category: filter.category }),
      per_page: 8,
      page: filter.page || 1,
    };
    
    const res = await axios.get(${LMSURL}/wp-json/learnpress/v1/courses, {
      params,
    });
    

    In this case, filter.category is set to the value 66, 67.

    The API request works, but the response includes duplicate courses likely because some courses belong to both categories.

    My question is:
    Is there a way to retrieve only unique courses ( no duplicates), even if they belong to both categories, using the LearnPress REST API itself?

    • This topic was modified 1 year, 1 month ago by isuru24.

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Plugin Support brianvu-tp

    (@briantp)

    Hi isuru24,

    Thank you for contacting us.

    You can modify your fetchCourses function using a Map to ensure uniqueness:

    const fetchCourses = async (filter) => {
    const params = {
    …(filter.search && { search: filter.search }),
    …(filter.category && { category: filter.category }),
    per_page: 100, // Temporarily increase to get all potential results
    page: filter.page || 1,
    };

    const res = await axios.get(
    ${LMSURL}/wp-json/learnpress/v1/courses, {
    params,
    });

    // Deduplicate courses based on course ID using Map
    const uniqueCourses = Array.from(
    new Map(res.data.map(course => [course.id, course])).values()
    );

    // Handle pagination manually if needed
    const pageSize = 8;
    const startIndex = (filter.page - 1) * pageSize || 0;
    const paginatedCourses = uniqueCourses.slice(startIndex, startIndex + pageSize);

    return {
    courses: paginatedCourses,
    total: uniqueCourses.length,
    totalPages: Math.ceil(uniqueCourses.length / pageSize)
    };
    };

    Best regards,
    Brianvu-tp

Viewing 1 replies (of 1 total)

The topic ‘Rest API Category Filter’ is closed to new replies.