LMS & eLearning

Creating a Filterable LearnDash Course Catalog With WP_Query

Build a server-rendered LearnDash course catalog with category, price type and keyword filters in clean URLs, using WP_Query, the LearnDash course taxonomies, the _ld_price_type meta and the Product model for prices.

Creating a Filterable LearnDash Course Catalog With WP_Query

The Course Grid add-on and the core course list cover most catalogs, but some sites need a catalog that is fully server rendered, crawlable on every filter combination, and shaped exactly to the design. That calls for a template built on WP_Query. This tutorial builds one for LearnDash 4.18.0.1 with three filters, category, price type and keyword, in plain query-string URLs, plus pagination and buttons that change for enrolled learners. Every LearnDash function and meta key used here exists in the plugin source.

What the catalog can filter on

  • LearnDash course taxonomies. ld_course_category and ld_course_tag, with rewrite slugs course-category and course-tag, are registered only when enabled under LearnDash, Courses, Settings, Taxonomies. The same screen can also attach the core WordPress categories and tags to courses. Pick one set and stick with it; the code below uses the LearnDash category.
  • Price type. The course access mode, open, free, paynow, subscribe or closed, is stored inside the serialized course settings, which you cannot query efficiently. LearnDash also mirrors it to its own post meta key, _ld_price_type, whenever the setting is saved, and the admin course list uses that key for its own price filter. That makes it safe for a meta_query.
  • Keyword. The standard s argument searches titles and content.

If courses were imported or created before the mirror existed, re-save them once, or run a bulk edit, so every course has the meta.

The query

<?php
/**
 * Build catalog query args from the request.
 *
 * @return array
 */
function wwc_catalog_query_args() {
    $paged    = max( 1, absint( get_query_var( 'paged' ) ) );
    $category = isset( $_GET['topic'] ) ? sanitize_title( wp_unslash( $_GET['topic'] ) ) : '';
    $price    = isset( $_GET['access'] ) ? sanitize_key( $_GET['access'] ) : '';
    $search   = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : '';

    $args = array(
        'post_type'      => learndash_get_post_type_slug( 'course' ),
        'post_status'    => 'publish',
        'posts_per_page' => 12,
        'paged'          => $paged,
        'orderby'        => 'menu_order title',
        'order'          => 'ASC',
    );

    if ( $category ) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'ld_course_category',
                'field'    => 'slug',
                'terms'    => $category,
            ),
        );
    }

    $allowed_prices = array( 'open', 'free', 'paynow', 'subscribe', 'closed' );
    if ( in_array( $price, $allowed_prices, true ) ) {
        $args['meta_query'] = array(
            array(
                'key'   => '_ld_price_type',
                'value' => $price,
            ),
        );
    }

    if ( '' !== $search ) {
        $args['s'] = $search;
    }

    return $args;
}

The filter parameters are named topic, access and q on purpose. Using s or a taxonomy's own query var on a normal page would make WordPress treat the request as a search or archive and replace your page; neutral names avoid that.

The filter form

<?php
function wwc_catalog_filter_form() {
    $terms   = get_terms( array( 'taxonomy' => 'ld_course_category', 'hide_empty' => true ) );
    $current = array(
        'topic'  => sanitize_title( wp_unslash( $_GET['topic'] ?? '' ) ),
        'access' => sanitize_key( $_GET['access'] ?? '' ),
        'q'      => sanitize_text_field( wp_unslash( $_GET['q'] ?? '' ) ),
    );
    $prices  = array(
        ''          => __( 'Any access', 'wwc' ),
        'free'      => __( 'Free', 'wwc' ),
        'paynow'    => __( 'One-time purchase', 'wwc' ),
        'subscribe' => __( 'Subscription', 'wwc' ),
        'open'      => __( 'Open to all', 'wwc' ),
    );
    ?>
    <form class="wwc-catalog-filters" method="get" action="<?php echo esc_url( get_permalink() ); ?>">
        <input type="search" name="q" value="<?php echo esc_attr( $current['q'] ); ?>" placeholder="<?php esc_attr_e( 'Search courses', 'wwc' ); ?>">
        <select name="topic">
            <option value=""><?php esc_html_e( 'All topics', 'wwc' ); ?></option>
            <?php foreach ( (array) $terms as $term ) : ?>
                <option value="<?php echo esc_attr( $term->slug ); ?>" <?php selected( $current['topic'], $term->slug ); ?>><?php echo esc_html( $term->name ); ?></option>
            <?php endforeach; ?>
        </select>
        <select name="access">
            <?php foreach ( $prices as $value => $label ) : ?>
                <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current['access'], $value ); ?>><?php echo esc_html( $label ); ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit"><?php esc_html_e( 'Filter', 'wwc' ); ?></button>
    </form>
    <?php
}

A GET form produces URLs such as /courses/?topic=compliance&access=free, which search engines can crawl and visitors can bookmark. Leave Closed out of the visitor-facing dropdown, since closed courses are usually sold elsewhere.

The card loop

<?php
/**
 * Escaped anchor for catalog cards.
 *
 * @param string $url   Link target.
 * @param string $text  Link text.
 * @param array  $attrs Extra attributes.
 * @return string
 */
function wwc_catalog_link( $url, $text, $attrs = array() ) {
    $attrs     = array_merge( array( 'href' => esc_url( $url ) ), $attrs );
    $attr_html = '';
    foreach ( $attrs as $attr_name => $attr_value ) {
        $attr_html .= sprintf( ' %1$s="%2$s"', esc_attr( $attr_name ), esc_attr( $attr_value ) );
    }
    return '<a' . $attr_html . '>' . esc_html( $text ) . '</a>';
}

function wwc_render_catalog() {
    $query   = new WP_Query( wwc_catalog_query_args() );
    $user_id = get_current_user_id();

    wwc_catalog_filter_form();

    if ( ! $query->have_posts() ) {
        echo '<p>' . esc_html__( 'No courses match those filters.', 'wwc' ) . '</p>';
        return;
    }

    echo '<div class="wwc-catalog">';

    while ( $query->have_posts() ) {
        $query->the_post();
        $course_id = get_the_ID();
        $product   = \LearnDash\Core\Models\Product::find( $course_id );
        $enrolled  = $user_id && sfwd_lms_has_access( $course_id, $user_id );

        echo '<article class="wwc-card">';
        if ( has_post_thumbnail() ) {
            the_post_thumbnail( 'medium_large' );
        }
        echo '<h2>' . wwc_catalog_link( get_permalink(), get_the_title() ) . '</h2>'; // phpcs:ignore WordPress.Security.EscapeOutput -- escaped in helper.
        echo '<p>' . esc_html( wp_trim_words( get_the_excerpt(), 24 ) ) . '</p>';

        if ( $enrolled ) {
            $p = learndash_course_progress( array( 'user_id' => $user_id, 'course_id' => $course_id, 'array' => true ) );
            echo '<p class="wwc-card__status">' . esc_html( sprintf( __( '%d%% complete', 'wwc' ), absint( $p['percentage'] ?? 0 ) ) ) . '</p>';
            echo wwc_catalog_link( get_permalink(), __( 'Continue', 'wwc' ), array( 'class' => 'ld-button' ) ); // phpcs:ignore WordPress.Security.EscapeOutput
        } elseif ( $product ) {
            $price = $product->get_display_price();
            echo '<p class="wwc-card__price">' . esc_html( '' !== $price ? $price : __( 'Free', 'wwc' ) ) . '</p>';
            echo wwc_catalog_link( get_permalink(), __( 'View course', 'wwc' ), array( 'class' => 'ld-button' ) ); // phpcs:ignore WordPress.Security.EscapeOutput
        }

        echo '</article>';
    }

    echo '</div>';

    echo wp_kses_post(
        paginate_links(
            array(
                'total'   => $query->max_num_pages,
                'current' => max( 1, absint( get_query_var( 'paged' ) ) ),
            )
        )
    );

    wp_reset_postdata();
}

\LearnDash\Core\Models\Product::find() returns the product model for a course or group, or null, and get_display_price() returns the course price formatted with the site currency, passed through the filter learndash_model_product_display_price. Open and free courses have no price, so the card prints Free instead. The method does not append a subscription interval; for subscription courses, read the interval and frequency from learndash_get_course_price( $course_id ), which returns them as interval and frequency keys, and add them after the price. For enrolled learners the card swaps the price for progress, using sfwd_lms_has_access() and learndash_course_progress() in array mode.

Wiring it into a page

Register a shortcode that buffers the output, add_shortcode( 'wwc_catalog', function () { ob_start(); wwc_render_catalog(); return ob_get_clean(); } );, and place it on a Courses page, or call wwc_render_catalog() from a page template. paginate_links() preserves the query string, so filters survive paging. If your permalinks use /courses/ for the LearnDash archive, either give the catalog page a different slug or turn off the course archive option under LearnDash, Courses, Settings to avoid a clash.

SEO details

Filtered pages are real URLs, which is the point, but you do not want hundreds of combinations indexed. Add a canonical pointing at the unfiltered catalog for keyword searches, and allow indexing of single-category views, which make good landing pages. Write a short introduction per category in the term description and print it above the grid when a topic is selected. This is where a custom catalog beats AJAX-driven grids, as discussed in our comparison of Course Grid, Course List, Query Loop and custom queries.

Performance

The query itself is a normal post query with one taxonomy join and one meta join, both indexed by WordPress. The per-card costs are the product lookup and, for logged-in users, an access check and progress read. With twelve cards per page this is fast. Cache the visitor version of the page normally; for logged-in users either skip page caching or move the enrolled-state elements into a small JavaScript request so the main grid can stay cached.

Two additions come up on almost every catalog. A featured row at the top can be a second, small query for courses tagged with a "featured" course tag, excluded from the main query with post__not_in so they do not appear twice. A sort control, newest, title or most popular, maps to orderby values: date, title, or menu_order if editors order courses by hand. Avoid sorting by enrollment count in the query; LearnDash does not store a single count field, so compute popularity in a nightly job and save it as post meta you can sort on with meta_value_num.

Testing

Enable the course category taxonomy, assign categories, and confirm each filter alone and in combination. Re-save one course and check _ld_price_type appears in its custom fields. Visit as a visitor, an enrolled learner and an administrator, since administrators have access to everything and will see Continue on every card. Check page two of a filtered result keeps the filters, and that an unknown access value is ignored rather than returning nothing.

When to get help

A catalog like this takes a day including design. Faceted search across many attributes, instructor filters, multi-currency prices or catalogs that mix LearnDash with WooCommerce products are bigger projects; our LearnDash services team builds them, and a LearnDash developer can add instant filtering on top of the server-rendered version.

Frequently asked questions

How do I filter LearnDash courses by price type in WP_Query?

Use a meta_query on _ld_price_type, which LearnDash writes alongside the course settings. The values are open, free, paynow, subscribe and closed.

Why are my course categories missing?

The LearnDash course taxonomies are only registered when enabled under the Courses taxonomy settings. Turn them on, then assign terms.

How do I show a formatted course price?

Load the product model with Product::find() and print get_display_price(), which applies the site currency. For subscriptions, add the interval from learndash_get_course_price().

Can enrolled learners see different buttons?

Yes. Check sfwd_lms_has_access() per card and show progress and a Continue button instead of the price.

Add WorldWin Coder to your preferred sources

Add worldwincoder.com as a preferred source on Google, or open this article in your AI assistant to use it as a source.

· Developers and project managers

Articles written and reviewed by the developers and project managers at WorldWin Coder, who build and maintain websites, web applications and mobile apps on WordPress, Moodle, PHP, Laravel, CodeIgniter and Flutter.

Free consultation

Need help with WordPress?

Tell us what you are working on. A developer who does this every week reads your message and replies within one business day with next steps and a free quote.

  • Free consultation and quote
  • NDA on request
  • You own the source code
  • Reply within one business day

Tell us about your project

Add budget and timeline optional, helps us quote faster

This form is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Keep reading

Have something to build, fix or move?

Tell us where you are. A developer reads every inquiry, and you get next steps and a free quote within one business day.