# Members-Only Download Links

> Adds a [wpide_member_download id="123"] shortcode that gives logged-in members a personal download link for a Media Library file and shows visitors a login link instead.

- Type: PHP
- Runs: Run everywhere
- Category: [Memberships](https://wpide.com/library/category/memberships/)
- Tags: downloads, members, files
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/members-only-download-links/

## Code

```php
add_shortcode( 'wpide_member_download', function ( $atts ) {
    $atts = shortcode_atts( array( 'id' => 0, 'label' => 'Download' ), $atts, 'wpide_member_download' );
    $id   = absint( $atts['id'] );

    if ( ! $id || 'attachment' !== get_post_type( $id ) ) {
        return '';
    }

    if ( ! is_user_logged_in() ) {
        return '<a class="wpide-member-download is-locked" href="' . esc_url( wp_login_url( get_permalink() ) ) . '">' . esc_html( 'Log in to download' ) . '</a>';
    }

    $url = wp_nonce_url( add_query_arg( 'wpide_download', $id, home_url( '/' ) ), 'wpide_download_' . $id );

    return '<a class="wpide-member-download" href="' . esc_url( $url ) . '">' . esc_html( $atts['label'] ) . '</a>';
} );

add_action( 'init', function () {
    if ( empty( $_GET['wpide_download'] ) ) {
        return;
    }

    $id = absint( $_GET['wpide_download'] );

    if ( ! is_user_logged_in() ) {
        auth_redirect();
    }

    if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'wpide_download_' . $id ) ) {
        wp_die( 'This download link has expired. Please go back and click it again.', 'Download', array( 'response' => 403 ) );
    }

    $file    = get_attached_file( $id );
    $uploads = wp_get_upload_dir();

    if ( 'attachment' !== get_post_type( $id ) || ! $file || ! is_readable( $file ) || 0 !== strpos( wp_normalize_path( realpath( $file ) ), wp_normalize_path( realpath( $uploads['basedir'] ) ) ) ) {
        wp_die( 'File not found.', 'Download', array( 'response' => 404 ) );
    }

    nocache_headers();
    header( 'Content-Type: ' . ( get_post_mime_type( $id ) ? get_post_mime_type( $id ) : 'application/octet-stream' ) );
    header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( wp_basename( $file ) ) . '"' );
    header( 'Content-Length: ' . filesize( $file ) );
    header( 'X-Content-Type-Options: nosniff' );

    while ( ob_get_level() ) {
        ob_end_clean();
    }

    readfile( $file );
    exit;
} );
```

## Notes

Links are tied to the member's session, so shared links do not work for others. The file's normal uploads URL is still public unless your server blocks it.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Members-Only Download Links" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
