How to Create an AI YouTube Hashtag Generator Tool in WordPress

WhatsApp
Telegram
Facebook
Twitter
LinkedIn

If you’ve been looking for a way to create a profitable website, building an AI-powered tool site could be your golden opportunity. With advancements in AI technology, you can leverage APIs like Google’s Gemini to create tools that users find helpful and valuable. In this guide, I’ll show you how to create an AI YouTube Hashtag Generator tool in WordPress. This tool will let users quickly generate relevant hashtags for their YouTube videos—essential for boosting discoverability and reach.

Beyond just providing a valuable resource, this type of site can become a steady income source. You can monetize it using Google AdSense, allowing you to earn revenue every time a user interacts with the tool or visits your site. The more visitors you attract, the more you earn.

Key Steps for Creating an AI-Powered YouTube Hashtag Generator

To create this AI hashtag generator, you’ll set up a WordPress site, install a custom code plugin, add an AI-powered code snippet, and display the tool on a page. Here’s a breakdown of what we’ll cover:

  1. Access the WordPress Dashboard: Log in to your WordPress dashboard to begin setup.
  2. Install WPCode Lite Plugin: This plugin allows you to add custom code without modifying core WordPress files.
  3. Add a Code Snippet: Insert a PHP snippet with your custom AI code.
  4. Configure the API and Settings: Adjust the code to use the Gemini API for hashtag generation.
  5. Create a Display Page: Add a page to show the hashtag generator.
  6. Insert a Shortcode and Publish: Add the shortcode for displaying the tool.
  7. Monetize with Google AdSense: Add AdSense ads to your site for monetization.
  8. Test and Optimize: Ensure everything works and is set up for a great user experience.

Let’s dive into the detailed steps to get your site up and running.

Step 1: Go to Your WordPress Dashboard

To begin, log in to your WordPress website and navigate to the main dashboard. This is where you manage your site, add plugins, create pages, and control all other aspects of your website.

Step 2: Go to Plugins and Add New

In the WordPress dashboard menu, locate the Plugins section. Click on Add New to open the plugin library, where you can search for plugins that will help you add new functionality to your site.

Step 3: Install and Activate the “WPCode Lite” Plugin

AI YouTube Hashtag Generator Tool

In the plugin search bar, type “WPCode Lite” and hit enter. WPCode Lite is a popular WordPress plugin that allows you to add custom code snippets without directly editing your theme’s files. This is particularly useful for adding functions to your site safely and effectively.

  • Find WPCode Lite in the results.
  • Click Install and then Activate.

Once activated, you’ll see the WPCode Lite menu appear in your dashboard.

Step 4: Add a New Snippet in WPCode Lite

New Snippet in WPCode Lite

Now that WPCode Lite is installed and active, you can use it to add the code for your AI-powered YouTube hashtag generator.

  1. Navigate to WPCode Lite in your dashboard.
  2. Click on Add New Snippet to open the code editor.
  3. In the editor, select the PHP Snippet option. This tells WordPress that you’ll be adding PHP code.

Step 5: Add Your Code and Customize API

Once the PHP snippet editor opens, paste the following code into it. Replace the placeholder text in the code with your API information:

// Function to generate hashtags using Gemini API with prompt
function geneatename($prompt, $input, $apiKey)
{
$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={$apiKey}";

$postData = json_encode([
"contents" => [
[
"parts" => [
["text" => $prompt . ' ' . $input] // Combine prompt and input
]
]
],
"generationConfig" => [
"temperature" => 0.9,
"topK" => 1,
"topP" => 1,
"maxOutputTokens" => 1500, // Adjust as necessary
"stopSequences" => []
],
"safetySettings" => [
[
"category" => "HARM_CATEGORY_HARASSMENT",
"threshold" => "BLOCK_ONLY_HIGH"
],
[
"category" => "HARM_CATEGORY_HATE_SPEECH",
"threshold" => "BLOCK_ONLY_HIGH"
],
[
"category" => "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold" => "BLOCK_ONLY_HIGH"
],
[
"category" => "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold" => "BLOCK_ONLY_HIGH"
]
]
]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
]);

$response = curl_exec($ch);
curl_close($ch);

$responseData = json_decode($response, true);

if (isset($responseData['candidates'][0]['content']['parts'][0]['text'])) {
return $responseData['candidates'][0]['content']['parts'][0]['text'];
} else {
return "No generated hashtags found.";
}
}

add_action('wp_ajax_generate_name_json', 'generate_name_json');
add_action('wp_ajax_nopriv_generate_name_json', 'generate_name_json');

function generate_name_json()
{
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$videoInput = isset($_POST['videoInput']) ? $_POST['videoInput'] : '';
$numHashtags = isset($_POST['numHashtags']) ? intval($_POST['numHashtags']) : 30; // Default to 30 if not provided

$prompt = 'I Want You To Work As A Youtube Seo Expert Who Knowes Everything About Youtube Seo. My Main Gole Is To Rank Or Virel My Youtube Video About The Topic I Am Going To Give You. So You Have To Generate The Best Treanding Hastags For The Topic Generate A Minimum ' . $numHashtags . ' Hastags, Generate higly related highquality hastags that related to the topic or title. This Is Most Important To Not Add Any Other Unwanted Text Or Characters As It Breaks The Flow And Only Generates Hashtags. and generate the Hastags In JSON Formet Like The Example

{
"hashtags": [
{
"hashtag": "#WebDevelopment"
},
{
"hashtag": "#WebDevelopmentPodcast"
},
{
"hashtag": "#WebDevelopmentCareer"
}
]
}

gnerate the output same as i said dont add or remove anything like (```json) .
Now Generate ' . $numHashtags . ' hashtags For:'; // Your prompt

$geminiApiKey = 'YOUR_API_KEY';
$description = geneatename($prompt, $videoInput, $geminiApiKey);

// Return the generated description as JSON
echo json_encode(['description' => $description]);
exit;
}
}

function hashtags_generator()
{
ob_start(); ?>
<div class="form-container">

<form id="youtubedescriptionForm" method="POST">
<div class="form-group">
<textarea id="videoInput" name="videoInput" rows="3" cols="30" placeholder="Enter a description for your name, for example: names for my youtube channel related to tech" required></textarea>

<input type="number" id="numHashtags" name="numHashtags" min="1" value="10" placeholder="Number of Hashtags" required>

<button type="submit" id="generateButton">
<i class="fa-solid fa-wand-magic-sparkles"></i> Generate Hastags
</button>
</div>
</form>

<div id="result" style="display:none;">
<div id="descriptionContainer" class="description-container"></div>
<div class="action-buttons">
<button id="copyAllButton" class="action-button"><i class="fa-regular fa-copy"></i>Copy All</button>
<button id="copySelectedButton" class="action-button"><i class="fa-regular fa-copy"></i>Copy Selected</button>
</div>
</div>
</div>

<style>
input[type="number"] {
padding: 10px; /* Padding for better touch targets */
border: 1px solid #00949C;
border-radius: 5px; /* Rounded corners */
font-size: 16px; /* Font size */
transition: border-color 0.3s; /* Smooth transition for border color */
}

.form-container {
max-width: 800px;
margin: 0px auto;
background-color: white;
padding: 10px;
border-radius: 8px;
align-items: center;
justify-content: center;
}

.form-group {
display: flex;
flex-direction: column;
margin-bottom: 20px;
}

textarea, input {
padding: 12px;
margin-bottom: 15px;
border: 1px solid #00949C;
border-radius: 5px;
font-size: 16px;
font-weight: 500;
font-family: 'Karla', Sans-serif !important;
margin-bottom:10px !important;
}

button {
display: flex;
font-weight: 500;
align-items: center;
justify-content: center;
padding: 10px 20px;
border: none;
border-radius: 5px !important;
background-color: #00949C;
color: #fff;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s;
}

button i {
margin-right: 8px;
}

.description-output {
white-space: pre-wrap;
width: 100%;
height: auto;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #00949C;
border-radius: 5px;
background-color: #FFFFFF;
overflow-y: auto;
font-family: 'Karla', Sans-serif !important;
}

.description-box h3 {
font-size: 16px;
font-family: 'Karla', Sans-serif !important;
font-weight: 600;
color: #333;
margin-bottom: 0px;
}

h2 {
align-items: center;
font-size: 30px;
font-family: 'Poppins';
font-weight: 600;
color: #333;
margin-bottom: 10px;
}

.description-box {
position: relative;
border: 1px solid #00949C;
border-radius: 5px;
padding: 10px;
background-color: #f9f9f9;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
}

.description-box.selected {
background-color: #d1e9e3;
}

.description-box .check-icon {
display: none;
color: white;
font-size: 15px;
background-color: green;
border-radius: 50%;
padding: 5px;
margin-left: 5px;
}

.description-box.selected .check-icon {
display: inline;
}

.action-buttons {
display: flex;
justify-content: space-between;
margin-top: 20px;
}

.action-buttons button {
width: 48%;
}

#descriptionContainer {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
</style>

<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/js/all.min.js"
integrity="sha384-k6RqeWeci5ZR/Lv4MR0sA0FfDOMp8MX7z4B2W4rPQQpSCAc0EalL78P2Ik5owxQp"
crossorigin="anonymous"></script>

<script>
document.getElementById('youtubedescriptionForm').addEventListener('submit', function (event) {
event.preventDefault();
var videoInput = document.getElementById('videoInput').value;
var numHashtags = document.getElementById('numHashtags').value;

var xhr = new XMLHttpRequest();
xhr.open('POST', '<?php echo admin_url('admin-ajax.php'); ?>?action=generate_name_json', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

document.getElementById('generateButton').innerHTML = '<i class="fa fa-spinner fa-spin"></i> Generating Hashtags';

xhr.onload = function () {
document.getElementById('generateButton').innerHTML = '<i class="fa fa-sync-alt"></i> Regenerate Hashtags';
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
var descriptionContainer = document.getElementById('descriptionContainer');
descriptionContainer.innerHTML = '';

var descriptions = JSON.parse(response.description);

descriptions.hashtags.forEach(function (item) {
var descriptionBox = document.createElement('div');
descriptionBox.classList.add('description-box');
descriptionBox.setAttribute('data-hashtag', item.hashtag);

var h3 = document.createElement('h3');
h3.textContent = item.hashtag;

var checkIcon = document.createElement('i');
checkIcon.classList.add('check-icon', 'fa', 'fa-check');

descriptionBox.appendChild(h3);
descriptionBox.appendChild(checkIcon);
descriptionContainer.appendChild(descriptionBox);

descriptionBox.addEventListener('click', function () {
descriptionBox.classList.toggle('selected');
});
});

document.getElementById('result').style.display = 'block';
} else {
alert('An error occurred while generating the names.');
}
};

xhr.send('videoInput=' + encodeURIComponent(videoInput) + '&numHashtags=' + encodeURIComponent(numHashtags));
});

document.getElementById('copyAllButton').addEventListener('click', function () {
var allHashtags = document.querySelectorAll('.description-box h3');
var hashtagsText = Array.from(allHashtags).map(h => h.textContent).join(' ');
copyToClipboard(hashtagsText);
});

document.getElementById('copySelectedButton').addEventListener('click', function () {
var selectedHashtags = document.querySelectorAll('.description-box.selected h3');
var hashtagsText = Array.from(selectedHashtags).map(h => h.textContent).join(' ');
copyToClipboard(hashtagsText);
});

function copyToClipboard(text) {
var tempInput = document.createElement('input');
tempInput.value = text;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
alert('Hashtags copied to clipboard: ' + text);
}
</script>
<?php return ob_get_clean();
}

add_shortcode('hashtags_generator', 'hashtags_generator');

Explanation of the Code:

  • The function generate_youtube_hashtags takes a keyword entered by the user and calls an external API to generate hashtags.
  • The API key and endpoint should be replaced with your actual API details.
  • The shortcode [hashtags_generator] is created to embed the form on any page.

Step 6: Change the API Key and Endpoint

In the code above, replace the placeholder values:

  • YOUR_API_KEY: This should be the API key provided by your chosen AI API service.

Once you have made these changes, save the snippet by clicking Save and Activate.

Step 7: Create a Page in WordPress to Display the Tool

To display your hashtag generator, create a new page on your WordPress site.

  1. Go to Pages in your WordPress dashboard.
  2. Click Add New.
  3. Title your page (e.g., “YouTube Hashtag Generator”).
  4. In the content editor, add a description or instructions for users, if you’d like.

Step 8: Add the Shortcode to Display the Hashtag Generator

Inside the content editor of the new page, add the following shortcode where you want the hashtag generator tool to appear:

plaintextCopy code[youtube_hashtag_generator]

This shortcode will load the form and functionality of the YouTube hashtag generator wherever you place it on the page.

After adding the shortcode, publish the page to make it live.

Step 9: Test and Finalize

Visit the page you created to test the hashtag generator tool. Enter a sample keyword to ensure that:

  1. The form accepts user input correctly.
  2. The API call is functioning as expected, and relevant hashtags are generated.
  3. The output displays clearly on the page without errors.

If there are any issues, double-check that:

  • The API key and endpoint URL are correct.
  • The WPCode Lite snippet is activated.
  • The shortcode [youtube_hashtag_generator] is correctly inserted on the page.

Additional Tips for Enhancing Your AI YouTube Hashtag Generator

If you want to enhance the tool further, consider these optional features:

  • Styling: Customize the look of the form using CSS to match your website’s design.
  • Error Handling: Improve error messages so users understand what might be going wrong, especially if the API call fails.
  • Validation: Add client-side validation using JavaScript to ensure users input a valid keyword before submitting the form.
  • Cache Hashtags: If the same keywords are frequently used, you could cache the hashtags to reduce API calls and load time.

Conclusion

You now have a functional, AI-powered YouTube hashtag generator tool on your WordPress site. By leveraging the WPCode Lite plugin, you can safely and easily integrate custom functionality like this without editing your WordPress theme files directly. This tool will add value for your users by helping them quickly generate hashtags, improving their content’s SEO and visibility on YouTube.

With some customization and additional features, you can further enhance the tool’s functionality and user experience. By following the steps in this guide, you’re well on your way to creating helpful AI tools on WordPress that make content creation easier and more effective.

Wait a moment

WPHub AI Chatbot
Offline
Add a free AI chatbot to your website by