Related Downloads Below Each Download
Lists up to four other downloads from the same category below each download's content, helping buyers discover more of your products.
Opens WPIDE on
Code
$wpide_edd_related_count = 4; // Downloads to show.
add_action( 'edd_after_download_content', function ( $download_id ) use ( $wpide_edd_related_count ) {
$ids = get_transient( 'wpide_edd_related_' . $download_id );
if ( false === $ids ) {
$terms = wp_get_post_terms( $download_id, 'download_category', array( 'fields' => 'ids' ) );
$ids = array();
if ( $terms && ! is_wp_error( $terms ) ) {
$ids = get_posts( array(
'post_type' => 'download',
'post_status' => 'publish',
'posts_per_page' => $wpide_edd_related_count,
'post__not_in' => array( $download_id ),
'fields' => 'ids',
'no_found_rows' => true,
'orderby' => 'rand',
'tax_query' => array( array( 'taxonomy' => 'download_category', 'terms' => $terms ) ), // phpcs:ignore WordPress.DB.SlowDBQuery
) );
}
set_transient( 'wpide_edd_related_' . $download_id, $ids, $ids ? 12 * HOUR_IN_SECONDS : HOUR_IN_SECONDS );
}
if ( ! $ids ) {
return;
}
echo '<section class="wpide-edd-related"><h3>' . esc_html( 'You may also like' ) . '</h3><ul style="display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:1em;list-style:none;padding:0">';
foreach ( $ids as $id ) {
printf(
'<li><a href="%1$s">%2$s<span style="display:block;margin-top:.4em">%3$s</span></a>%4$s</li>',
esc_url( get_permalink( $id ) ),
get_the_post_thumbnail( $id, 'medium', array( 'style' => 'width:100%;height:auto' ) ),
esc_html( get_the_title( $id ) ),
wp_kses_post( edd_price( $id, false ) )
);
}
echo '</ul></section>';
}, 20 );
add_action( 'save_post_download', function ( $post_id ) {
delete_transient( 'wpide_edd_related_' . $post_id );
} );
Notes
Results are cached for 12 hours per download, and downloads without a category show nothing.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.