How to Add an Ads.txt File to Your WordPress Website

Home » Snippets » How to Add an Ads.txt File to Your WordPress Website
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

If you’re looking to monetize your WordPress site through advertising, adding an ads.txt file is an essential step that will help prevent unauthorized ads from appearing on your site. Ads.txt is a simple text file that lists the companies authorized to sell ad inventory on your site. In this article, we’ll guide you through the process of adding an ads.txt file to your WordPress site.

					function wpturbo_add_ads_txt_file() {
    $ads_txt_content = "google.com, pub-1234567890123456, DIRECT, f08c47fec0942fa0nbing.com, pub-1234567890123456, DIRECT, f08c47fec0942fa0";
    $upload_dir = wp_upload_dir();
    $file_path = $upload_dir['basedir'] . '/ads.txt';
    file_put_contents( $file_path, $ads_txt_content );
}
add_action( 'admin_init', 'wpturbo_add_ads_txt_file' );
				

In this article, we will be discussing how to add an ads.txt file in WordPress. Ads.txt is an Interactive Advertising Bureau (IAB) initiative that helps prevent fraudulent activity in the digital advertising industry. This file is essentially a list of authorized digital sellers (ad networks, exchanges, direct advertisers) who are authorized to sell your inventory.

To add the ads.txt file to your WordPress site, we will use the file_put_contents() function to create the file and add the necessary content. The wpturbo_add_ads_txt_file() function is defined to handle the creation of the file in WordPress.

First, we define the variable $ads_txt_content that contains the content we want to put in the ads.txt file. This content should be a series of lines, each with a specific format. In this example, we are adding two advertising platforms: Google and Bing. Here is the format for one line in the file:

[ad platform domain], [publisher ID], [relationship type], [tag ID]

For example:

google.com, pub-1234567890123456, DIRECT, f08c47fec0942fa0

Once we have defined the content, we can use the wp_upload_dir() function to get the path to the WordPress uploads folder, where we will store the file. We define the file path as $upload_dir['basedir'] . '/ads.txt'.

Finally, we use the file_put_contents() function to create the ads.txt file and add the content. The function takes two parameters: the file path and the content we want to add. The contents of $ads_txt_content are written to the ads.txt file.

To ensure the function runs when the WordPress admin initializes, we hook it into the admin_init action using the add_action() function.

That’s it! With this snippet of code, you can add an ads.txt file to your WordPress site to help prevent fraudulent advertising activity.

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