Skip to main content

Register a custom related-episodes query strategy

Free Advanced

Use benecaster_related_episodes_query_types to add a custom query strategy to the benecaster_related_episodes shortcode and the related_episodes Episode Page block.

Any add-on can register one or more strategies; they appear automatically in the block config dropdown once registered. A strategy is a plain array — a label and a results callable. There is no interface to implement and no class name to know.

results receives ( int $episode_id, int $show_id, array $args ) and returns a list of WP_Post objects. $args carries count (int) and exclude_current (bool); honour both.

Episode ID first. The sibling filter benecaster_member_thanks_query_types takes the same two IDs in the opposite order — show first. Both are integers, so PHP will not catch a transposition; you will just get results for the wrong thing.

Tier-aware filtering is the renderer’s job, not yours. Return every matching published episode and let Benecaster hide what the viewer cannot access. A strategy that filters by tier itself will double-filter, and will go wrong the moment the viewer’s tier changes.

An entry whose results is missing or not callable is discarded silently, rather than fataling at render time. A strategy that never shows up in the dropdown is almost always a malformed definition, not a registration that failed.

Code

<?php
add_filter(
    'benecaster_related_episodes_query_types',
    function ( array $types ): array {
        $types['by_series'] = [
            'label'   => __( 'Same series', 'my-addon' ),
            'results' => function ( int $episode_id, int $show_id, array $args ): array {
                $series_id = get_post_meta( $episode_id, '_my_addon_series_id', true );

                if ( ! $series_id ) {
                    return [];
                }

                $count   = (int) ( $args['count'] ?? 5 );
                $exclude = (bool) ( $args['exclude_current'] ?? true );

                $all = get_posts( [
                    'post_type'      => 'benecaster_episode',
                    'post_status'    => 'publish',
                    'post_parent'    => $show_id,
                    'posts_per_page' => -1,
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                ] );

                $related = [];

                foreach ( $all as $post ) {
                    if ( $exclude && $post->ID === $episode_id ) {
                        continue;
                    }

                    if ( get_post_meta( $post->ID, '_my_addon_series_id', true ) === $series_id ) {
                        $related[] = $post;
                    }
                }

                return $count > 0 ? array_slice( $related, 0, $count ) : $related;
            },
        ];

        return $types;
    }
);

View on GitHub →

Hooks Used

Need this built rather than just documented? See our services →