Posted on

MemberPress Downloads add-on

The Downloads add-on for MemberPress adds downloadable files to MemberPress. These files are stored outside the Media Library, so by default Relevanssi attachment indexing has no access to them. However, Relevanssi offers filter hooks you can use to make Relevanssi index the MemberPress Downloads files.

Adjust the query

All this code goes to the child theme functions.php file. First we need to tell Relevanssi to look for mpdl-file posts instead of attachment posts using the relevanssi_get_attachment_posts_query filter hook. By default, Relevanssi looks for posts with the post type attachment, post status inherit and a suitable MIME type. These all need to be changed, because the Downloads posts have the post type mdpl-file, status of publish and no MIME type.

add_filter( 'relevanssi_get_attachment_posts_query', 'rlv_mpdl_query' );

/**
 * Filters the MySQL query for getting the attachments.
 *
 * Finds and replaces the 'attachment' post type restriction to look for mpdl-file
 * posts and also changes the post_status filtering from 'inherit' to 'publish'.
 *
 * @param string $query The MySQL query.
 *
 * @return string The modified query.
 */
function rlv_mpdl_query( string $query ) : string {
  return str_replace(
    "post_type = 'attachment' AND post_status = 'inherit' AND post_mime_type LIKE %s",
    "post_type = 'mpdl-file' AND post_status = 'publish' AND (post_mime_type LIKE %s OR post_mime_type = '')",
    $query
  );
}

Change the file name and path

Then you probably need to choose “Upload files for reading” in the Relevanssi attachment settings – as the files often have limited access – and thus you also need to use the relevanssi_get_attached_file filter hook to modify the name and path of the file sent to Relevanssi:

add_filter( 'relevanssi_get_attached_file', 'rlv_mpdl_file', 10, 2 );

/**
 * Filters the name and path of the file.
 *
 * Gets the file name from the _mpdl_file_filename custom field of the download file
 * post and corrects the path, too. If your files are stored somewhere else than
 * /wp-content/uploads/mpdl/, adjust the path.
 *
 * @param string $filename The original file name (not used).
 * @param int    $post_id  The post ID.
 *
 * @return string The adjusted file name and relative path.
 */
function rlv_mpdl_file( string $filename, int $post_id ) : string {
  $file       = get_post_meta( $post_id, '_mpdl_file_filename', true );
  $upload_dir = wp_get_upload_dir();
  $filename   = $upload_dir['basedir'] . '/mpdl/' . $file;

  return $filename;
}

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.