How to Create a Download Link in WordPress

Home » Snippets » How to Create a Download Link in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Do you have a file on your WordPress site that you want visitors to be able to download? Whether it’s a PDF, audio file, or image, adding a download link to your site can make it easy for users to access and download your content. In this article, we’ll cover the steps to create a download link in WordPress. From linking to media files to using plugins, we’ll provide various ways to add download links to your site.

					function wpturbo_download_link( $file_url, $file_name ) {
    echo "<a href='" . $file_url . "' download='" . $file_name . "'>Download " . $file_name . "</a>";
} 

// Usage example
wpturbo_download_link( 'http://example.com/file.pdf', 'My PDF File' );
				

In this tutorial, we’ll explain how to create a download link in WordPress using PHP. The snippet of code we’ll be using is a function called wpturbo_download_link(). This function takes in two parameters: $file_url and $file_name. The $file_url is the URL of the file you want to download, while the $file_name is the name that you want to give to the downloaded file.

function wpturbo_download_link( $file_url, $file_name ) {
    echo "<a href='" . $file_url . "' download='" . $file_name . "'>Download " . $file_name . "</a>";
}

Inside the function, we use echo to output an HTML link. The href attribute of the anchor tag is set to the $file_url value, which tells the browser where to find and download the file. The download attribute specifies the file name for the downloaded file. This attribute is optional, and if you don’t specify it, the downloaded file will have the same name as the original file.

The last part of the code $file_name is the name that will appear on the link. This is the friendly name displayed to the user and can be anything you’d like.

To use this function, simply pass in the required parameters to the function like the following;

wpturbo_download_link( 'http://example.com/file.pdf', 'My PDF File' );

This example creates a download link for a PDF file with the URL http://example.com/file.pdf, and the name "My PDF File". You can change the URL and name to match the file you want to offer for download.

Congratulations, you now know how to create a download link in WordPress using PHP.

Register an account to save your snippets or go Pro to get more features.