').append(
$('
').attr({ type: 'text', name: 'schema_properties[' + property + ']', id: 'siteseo_schema_property_' + property, class: 'widefat'}).val(defaultValue),
$('
').attr({ type: 'button', class: 'button siteseo-image-upload-btn'}).text('Upload Image'));
}else{
field = $('
').attr({ type: 'text', name: 'schema_properties[' + property + ']', id: 'siteseo_schema_property_' + property,
class: 'widefat'}).val(defaultValue);
}
$('
')
.append($('
').attr('for', 'siteseo_schema_property_' + property).text(label + ':'))
.append(field)
.appendTo(propertiesDiv);
}else if(typeof defaultValue === 'object'){
$.each(defaultValue, function(innerProp, innerVal){
if(innerProp === '@type') return;// Skip for inner $type property
let label = innerProp.replace(/([a-z])([A-Z])/g, '$1 $2');
label = label.charAt(0).toUpperCase() + label.slice(1);
if(is_textarea_fields.includes(innerProp)){
field = $('
').attr({ name: 'schema_properties[' + innerProp + ']', id: 'siteseo_schema_property_' + innerProp, rows: 3, class: 'widefat'}).val(innerVal);
} else if (is_date_type_fields.includes(innerProp)){
field = $('
').attr({ type: 'datetime-local', name: 'schema_properties[' + innerProp + ']', id: 'siteseo_schema_property_' + innerProp,
class: 'widefat'}).val(innerVal);
} else {
field = $('
').attr({ type: 'text', name: 'schema_properties[' + innerProp + ']', id: 'siteseo_schema_property_' + innerProp, required : (is_required_field.includes(innerProp) ? 'true' : 'false'),
class: 'widefat'}).val(innerVal);
}
$('
')
.append($('
').attr('for', 'siteseo_schema_property_' + innerProp).text(label + ':' + (is_required_field.includes(innerProp) ? ' (Required)*' : '')))
.append(field)
.appendTo(propertiesDiv);
});
}
});
// preview update
updatePreview();
$(document).on('input', '.siteseo-schema-properties input, #schema_properties textarea', updatePreview);
});
// preview function
function updatePreview(){
var schemaType = $('.siteseo_structured_data_type').val();
if(schemaType === 'CustomSchema'){
updateCustomSchemaPreview();
return;
}
var schemaData = {
'@context': 'https://schema.org',
'@type': schemaType
};
let podcastSchemaData = {
'@context': 'https://schema.org',
'@type': schemaType,
'associatedMedia' : {
'@type' : 'MediaObject',
},
'partOfSeason' : {
'@type' : 'PodcastSeason',
},
'partOfSeries' : {
'@type' : 'PodcastSeries',
}
};
$('.siteseo-schema-properties input, .siteseo-schema-properties textarea, .siteseo-schema-properties select').each(function(){
var propertyName = $(this).attr('name').match(/\[(.*?)\]/)[1];
var propertyValue = $(this).val();
if(propertyValue !== ''){
if(schemaType === 'PodcastEpisode'){
if(propertyName === 'contentUrl'){
podcastSchemaData['associatedMedia'][propertyName] = propertyValue;
}else if(['seasonName', 'seasonUrl', 'seasonNumber'].includes(propertyName)){
propertyName = (propertyName === 'seasonNumber') ? propertyName : propertyName.replace("season", "").toLowerCase();
podcastSchemaData['partOfSeason'][propertyName] = propertyValue;
}else if(['seriesName', 'seriesUrl'].includes(propertyName)){
podcastSchemaData['partOfSeries'][propertyName.replace("series", "").toLowerCase()] = propertyValue;
}else{
podcastSchemaData[propertyName] = propertyValue;
}
}else{
schemaData[propertyName] = propertyValue;
}
}
});
var jsonString = (schemaType === 'PodcastEpisode') ? JSON.stringify(podcastSchemaData, null, 2) : JSON.stringify(schemaData, null, 2);
$('#siteseo_raw_schema').text(jsonString);
// Make sure highlighter element exists
if($('.siteseo_schema_preview .siteseo_highlighter').length === 0){
$('.siteseo_schema_preview').html('
');
}
$('.siteseo_schema_preview .siteseo_highlighter').html(highlightJson(jsonString));
}
// Custom schema preview
function updateCustomSchemaPreview(){
var customSchema = $('.siteseo_structured_data_custom').val() || '';
$('#siteseo_raw_schema').text(customSchema);
// highlighter element exists
if($('.siteseo_schema_preview .siteseo_highlighter').length === 0){
$('.siteseo_schema_preview').html('
');
}
try{
if(customSchema.trim()){
var jsonObj = JSON.parse(customSchema);
$('.siteseo_schema_preview .siteseo_highlighter').html(highlightJson(jsonObj));
} else{
$('.siteseo_schema_preview .siteseo_highlighter').html('');
}
} catch(e){
$('.siteseo_schema_preview .siteseo_highlighter').text(customSchema);
}
}
// as per schema change update preview
$(document).on('input', '.siteseo_structured_data_custom', updateCustomSchemaPreview);
// Initial preview update
if($('.siteseo_structured_data_type').val() !== ''){
if($('.siteseo_structured_data_type').val() === 'CustomSchema'){
updateCustomSchemaPreview();
} else{
updatePreview();
$(document).on('input', '.siteseo-schema-properties input, .siteseo-schema-properties textarea', updatePreview);
}
}
/*** Refresh tokens ***/
$(document).on('click', '.siteseo-ai-refresh-tokens', function(e){
e.preventDefault();
e.stopPropagation();
let token_container = $(this).closest(".siteseo-ai-token-count");
token_container.addClass("siteseo-loading");
$('.siteseo-ai-token-badge').fadeOut(200).fadeIn(200);
$.ajax({
url: siteseo_pro.ajax_url,
method: "POST",
data: {
action: "siteseo_pro_refresh_tokens",
nonce: siteseo_pro.nonce,
},
success: function(res){
if(!res.success){
if(res.data){
snackbar(res.data);
return;
}
snackbar("Something went wrong fetching token data");
return;
}
update_tokens(res.data);
},
error: function(){
snackbar("Error refreshing tokens");
},
complete: function(){
token_container.removeClass("siteseo-loading");
}
});
});
function snackbar(msg){
if(!msg){
msg = 'Something went wrong!';
}
snack_bar = $('.siteseo-ai-snackbar');
snack_bar.text(msg);
snack_bar.show();
setTimeout(function(){ snack_bar.hide() }, 3500);
}
/** update tokens **/
function update_tokens(remaining_tokens){
let formatted_tokens = remaining_tokens < 0 ? 0 : parseInt(remaining_tokens).toLocaleString('en'),
token_badge = $('.siteseo-ai-token-badge');
if(token_badge.length === 0){
$('.siteseo-ai-token-count').prepend(
'
Tokens Remaining ' + formatted_tokens + ' ' +
'
' + '
'
);
} else{
let show_buy_link = remaining_tokens < 900 ? '
Buy AI Tokens ' : '';
token_badge.html('Tokens Remaining ' + formatted_tokens + show_buy_link);
}
}
// Open modal
$(document).on('click', '.siteseo-ai-modal-open', function(e){
e.preventDefault();
let context = $(this).data('context') || 0,
$modal = $('.siteseo-ai-modal-overlay');
if(typeof siteseo_universal !== 'undefined'){
$modal.data('context', context).show();
} else{
if(window.parent && window.parent !== window){
let $parentModal = window.parent.jQuery('.siteseo-ai-modal-overlay');
if($parentModal.length){
$parentModal.data('context', context).show();
add_input_fields();
return;
}
}
$modal.data('context', context).show();
}
// Update input fileds on tigger ai output
add_input_fields();
});
// Close modal
$('#siteseo-ai-close-modal').on('click', function(){
$('.siteseo-ai-modal-overlay').hide();
});
// Close when clicking outside
$(document).on('click', '.siteseo-ai-modal-overlay', function(e){
if($(e.target).is('.siteseo-ai-modal-overlay')){
let $modal = $('.siteseo-ai-modal-overlay');
if($modal.is(':visible')){
$modal.hide();
}
}
});
/** AI **/
$('.siteseo-ai-generate').on('submit', function(e){
e.preventDefault();
let context = $('#siteseo-ai').data('context'),
generate_title = $('input[name="generate_title"]').is(':checked'),
generate_desc = $('input[name="generate_desc"]').is(':checked');
$('.siteseo-ai-placeholder').remove();
$('.siteseo-ai-error').remove();
// Handling Universal metabox
let universal_metabox = document.querySelector('#siteseo-iframe-universal-metabox');
if(typeof siteseo_universal !== 'undefined' && context.length === 0 && universal_metabox && universal_metabox.contentWindow){
let universal_metabox_doc = universal_metabox.contentWindow.document,
$universal_metabox_visible = $(universal_metabox_doc).find('.siteseo-ai-modal-open:visible');
if($universal_metabox_visible.length){
context = $universal_metabox_visible.data('context');
}
}
let focus_keyword = $('.siteseo-ai-modal-body .siteseo-ai-input[type="text"]').eq(0).val(),
post_brief = $('.siteseo-ai-modal-body textarea').val(),
tone = $('.siteseo-ai-modal-body select').eq(0).val(),
audience = $('.siteseo-ai-modal-body select').eq(1).val(),
language = $('#siteseo-ai-language-select').val(),
num_titles = $('.siteseo-ai-modal-body input[type="number"]').val(),
spinner = $('.siteseo-ai-spinner');
if(!focus_keyword){
$('.siteseo-ai-error-msg').html('
Please enter the focus keyword.
');
return;
}
if(focus_keyword.length < 4){
$('.siteseo-ai-error-msg').html('
Focus keyword should be at least 4 characters long.
');
return;
}
if(!post_brief){
$('.siteseo-ai-error-msg').html('
Please enter the post summary.
');
return;
}
if(post_brief.length < 9){
$('.siteseo-ai-error-msg').html('
Post summary should be at least 9 characters long.
');
return;
}
if(!generate_title && !generate_desc){
$('.siteseo-ai-error-msg').html('
Please select at least one option (title or description) to proceed..
');
return;
}
$('.siteseo-ai-error').remove();
spinner.addClass('siteseo-ai-spinner-active');
let $button = $(this);
$('.siteseo-generate-animation').addClass('siteseo-ai-shimmer');
let prompt = (generate_title || generate_desc) ? build_prompt(focus_keyword, post_brief, tone, audience, language, num_titles, context, generate_title, generate_desc) : null;
if(!prompt){
return;
}
$.ajax({
url: siteseo_pro.ajax_url,
type: 'POST',
data: {
action: 'siteseo_pro_ai_generate',
prompt: prompt,
nonce: siteseo_pro.nonce
}
})
.then(function(response){
if(!response.success){
throw response.data;
}
if(response.data && response.data.remaining_tokens){
update_tokens(response.data.remaining_tokens);
}
return response.data.ai;
})
.then(function(response){
spinner.removeClass('siteseo-ai-spinner-active');
$button.prop('disabled', false);
if(!response.titles && generate_title && !generate_desc){
throw 'Unable to generate title';
} else if(!response.descriptions && generate_desc && !generate_title){
throw 'Unable to generate description';
} else if(!response.titles && !response.descriptions && generate_desc && generate_title){
throw 'Unable to generate title and description';
}
process_ai_response(response, generate_title, generate_desc);
})
.catch(function(error) {
spinner.removeClass('siteseo-ai-spinner-active');
$button.prop('disabled', false);
handle_error($button, error);
});
});
function build_prompt(focus_keyword, post_brief, tone, audience, lang, num, context, is_title = false, is_desc = false){
// Return early if nothing is requested.
if(!is_title && !is_desc){
return '';
}
// Use a simple map for platform context for easier maintenance.
const platform_map = {
og: 'OpenGraph (Facebook)',
twitter: 'X (Twitter)',
};
const platform_context = platform_map[context] || 'web page';
// Dynamically build the parts of the prompt.
const generate_parts = [];
const length_instructions = [];
const format_object = {};
if(is_title){
generate_parts.push('title');
length_instructions.push('each title must be between 50 and 60 characters');
format_object.titles = ['string', 'string']; // Example structure
}
if(is_desc){
generate_parts.push('description');
length_instructions.push('each description must be between 150 and 160 characters');
format_object.descriptions = ['string', 'string']; // Example structure
}
const generate = generate_parts.join(' and ');
const content_length = `The length of ${length_instructions.join(', and ')}.`;
const format = JSON.stringify(format_object);
// Building the final prompt.
return `Generate exactly ${num} SEO ${platform_context} ${generate} suggestions for a blog post with the following details:
- Focus Keyword: ${focus_keyword}
- Post Brief: ${post_brief}
- Tone: ${tone}
- Target Audience: ${audience}
- Language: ${lang}
It should be optimized for ${platform_context}, engaging, and ${content_length}
Return the response in json format like ${format} and do not include any extra text or explanation — only the raw JSON.`;
}
function process_ai_response(response, generate_title, generate_desc){
let titles = [];
let descriptions = [];
let title_target, desc_target,
copy_icon_svg = '
',
use_icon_svg = '
';
// Process if title res valid
if(typeof response.titles != 'undefined' && response.titles.length > 0){
titles = response.titles;
}
// Process desc res valid
if(typeof response.descriptions != 'undefined' && response.descriptions.length > 0){
descriptions = response.descriptions;
}
let title_html = '',
desc_html = '',
error_msg = '';
// Show tabs
if(titles.length > 0){
// Count existing titles plus new ones
let existingTitlesCount = $('.siteseo-ai-outputs-titles .siteseo-ai-item').length,
title_tab = $('.siteseo-ai-tab-btn[data-tab="siteseo-titles-tab"]');
title_tab.show().addClass('active');
title_tab.find('.siteseo-ai-tab-stat').text(existingTitlesCount + titles.length);
titles.forEach(function(title){
if(title.trim()){
title_html += `
${title.trim()}
${copy_icon_svg} Copy
${use_icon_svg} Use This
`;
}
});
} else {
if(generate_title){
let error_msg = titles < 1 ? 'No titles were generated' : '';
title_html += `
${error_msg}
`;
}
}
if(descriptions.length > 0){
// Count existing descriptions plus new ones
let existingDescCount = $('.siteseo-ai-outputs-desc .siteseo-ai-item').length;
desc_tab = $('.siteseo-ai-tab-btn[data-tab="siteseo-descriptions-tab"]');
desc_tab.show().addClass('active');
desc_tab.find('.siteseo-ai-tab-stat').text(existingDescCount + descriptions.length);
descriptions.forEach(function(desc){
if(desc.trim()){
desc_html += `
${desc.trim()}
${copy_icon_svg} Copy
${use_icon_svg} Use This
`;
}
});
} else {
if(generate_desc){
let error_msg = descriptions < 1 ? 'No descriptions were generated' : '';
desc_html += `
${error_msg}
`;
}
}
$('.siteseo-ai-tabs').show(); // Show the tabs
$('.siteseo-generate-animation').removeClass('siteseo-ai-shimmer');
if(title_html){
$('.siteseo-ai-outputs-titles').prepend(title_html);
}
if(desc_html){
$('.siteseo-ai-outputs-desc').prepend(desc_html);
}
add_input_fields();
if(generate_title || generate_desc){
$('.siteseo-ai-tab-btn').off('click').on('click', function(){
$('.siteseo-ai-tab-btn').removeClass('active');
$(this).addClass('active');
let tab_to_show = $(this).data('tab');
$('.siteseo-ai-tab-content').removeClass('active');
$('#' + tab_to_show).addClass('active');
});
// activate tab
if(generate_title && generate_desc){
$('.siteseo-ai-tab-btn[data-tab="siteseo-titles-tab"]').click();
} else if(generate_title){
$('.siteseo-ai-tab-btn[data-tab="siteseo-titles-tab"]').click();
} else if (generate_desc){
$('.siteseo-ai-tab-btn[data-tab="siteseo-descriptions-tab"]').click();
}
}
//copy and use buttons reset
$('.siteseo-ai-copy-btn').off('click').on('click', function(){
if($(this).hasClass('siteseo-ai-copy-btn')){
let text = $(this).data('text');
navigator.clipboard.writeText(text).then(function(){
let $btn = $(this);
$btn.html(`${use_icon_svg} Copied!`);
setTimeout(function(){
$btn.html(`${copy_icon_svg} Copy`);
}, 2000);
}.bind(this));
}
});
$('.siteseo-ai-use-btn').on('click', function(){
let text = $(this).data('text'),
target = $(this).data('target'),
context = $(this).closest('.siteseo-ai-modal-overlay').data('context');
// For universal metabox
let universal_metabox = document.querySelector('#siteseo-iframe-universal-metabox');
if(universal_metabox && universal_metabox.contentWindow){
let universal_metabox_doc = universal_metabox.contentWindow.document;
let universal_jQuery = universal_metabox.contentWindow.jQuery;
let actual_target;
switch(context){
case 'og':
actual_target = 'siteseo_social_fb_title_meta';
if($(this).attr('id') === 'siteseo-ai-desc') {
actual_target = 'siteseo_social_fb_desc_meta';
}
break;
case 'twitter':
actual_target = 'siteseo_social_twitter_title_meta';
if($(this).attr('id') === 'siteseo-ai-desc') {
actual_target = 'siteseo_social_twitter_desc_meta';
}
break;
default:
actual_target = 'siteseo_titles_title_meta';
if($(this).attr('id') === 'siteseo-ai-desc') {
actual_target = 'siteseo_titles_desc_meta';
}
}
let $universal_metabox_input = universal_jQuery(universal_metabox_doc).find('#' + actual_target);
if($universal_metabox_input.length){
$universal_metabox_input.val(text);
$universal_metabox_input.trigger('input');
}
} else {
// For regular metabox
let $input = $('#' + target);
if($input.length){
$input.val(text).trigger('input');
}
}
let $btn = $(this);
$btn.html(`${use_icon_svg} Applied!`);
setTimeout(function(){
$btn.html(`${use_icon_svg} Use This`);
}, 2000);
});
}
function add_input_fields(){
let $modal = $('.siteseo-ai-modal-open:visible');
let context = $modal.data('context');
if(!context){
let $modal = jQuery('.siteseo-ai-modal-open:visible');
context = $modal.data('context');
}
let title_target, desc_target;
switch(context){
case 'og':
title_target = 'siteseo_social_fb_title_meta';
desc_target = 'siteseo_social_fb_desc_meta';
break;
case 'twitter':
title_target = 'siteseo_social_twitter_title_meta';
desc_target = 'siteseo_social_twitter_desc_meta';
break;
default:
title_target = 'siteseo_titles_title_meta';
desc_target = 'siteseo_titles_desc_meta';
}
// Update all title buttons
$('.siteseo-ai-use-btn[id="siteseo-ai-titles"]').each(function(){
$(this).data('target', title_target);
});
// Update all description buttons
$('.siteseo-ai-use-btn[id="siteseo-ai-desc"]').each(function(){
$(this).data('target', desc_target);
});
}
function handle_error($button, error){
$button.prop('disabled', false);
$('.siteseo-ai-error-msg').html('
Error: ' + error + '
');
$('.siteseo-generate-animation').removeClass('siteseo-ai-shimmer');
}
// Tab switch
$('.siteseo-tab').on('click', function(){
$('.siteseo-tab').removeClass('active');
$(this).addClass('active');
let tab = $(this).data('tab');
$('.siteseo-ai-tab-content').removeClass('active');
$('.siteseo-ai-tab-content[data-tab="' + tab + '"]').addClass('active');
});
});
PK ! I; ; assets/js/admin.jsnu [ jQuery(document).ready(function($){
// robots.txt
$("#siteseo_googlebots, #siteseo_bingbots, #siteseo_yandex_bots, #siteseo_semrushbot, #siteseo_rss_feeds, #siteseo_gptbots, #siteseo_link_sitemap, #siteseo_wp_rule, #siteseo_majesticsbots, #siteseo_ahrefsbot, #siteseo_mangools, #siteseo_google_ads_bots, #siteseo_google_img_bot").on("click", function(){
let currentVal = $("#siteseo_robots_file_content").val();
let tagVal = $(this).attr("data-tag");
$("#siteseo_robots_file_content").val(currentVal + "\n" + tagVal);
});
// htaccess
$('#siteseo_block_dir, #siteseo_wp_config, #siteseo_error_300').on('click', function(){
let currentVal = $("#siteseo_htaccess_file").val();
let tagVal = $(this).attr("data-tag");
$("#siteseo_htaccess_file").val(currentVal + "\n" + tagVal);
});
$('#siteseopro-pagespeed-results .siteseo-metabox-tab-label').click(function(){
$('.siteseo-metabox-tab-label').removeClass('siteseo-metabox-tab-label-active');
$('.siteseo-metabox-tab').hide();
$(this).addClass('siteseo-metabox-tab-label-active');
var activeTab = $(this).data('tab');
$('.' + activeTab).show();
});
$('input[name="ps_device_type"]').on('change', function(){
jEle = jQuery(this),
val = jEle.val();
if(val == 'mobile'){
jQuery('#siteseo-ps-mobile').css('display', 'flex');
jQuery('#siteseo-ps-mobile').find('.siteseo-metabox-tab-label:first-child').trigger('click');
jQuery('#siteseo-ps-desktop').hide();
} else {
jQuery('#siteseo-ps-mobile').hide();
jQuery('#siteseo-ps-desktop').css('display', 'flex');
jQuery('#siteseo-ps-desktop').find('.siteseo-metabox-tab-label:first-child').trigger('click');
}
});
$('#siteseopro-pagespeed-btn').on('click', function(){
$('#siteseopro-pagespeed-results').empty();
let spinner = $(this).next(),
input = $(this).closest('div').find('input');
spinner.addClass('is-active'),
siteseo_pagespeed_request(input.val(), true);
siteseo_pagespeed_request(input.val(), false);
});
$('#siteseopro-clear-Page-speed-insights').on('click', function(){
$.ajax({
url: siteseo_pro.ajax_url,
type: 'POST',
data: {
action: 'siteseo_pro_pagespeed_insights_remove_results',
nonce: siteseo_pro.nonce
},
success: function(response){
$('#siteseopro-pagespeed-results').empty();
}
});
});
$('.siteseo-audit-title').next('.description').hide();
$('.siteseo-audit-title').on('click', function(e){
var description = $(this).next('.description');
var icon = $(this).find(".toggle-icon");
if(description.is(':visible')){
description.hide();
icon.addClass('class', 'toggle-icon dashicons dashicons-arrow-up-alt2');
} else {
description.show();
icon.addClass('class', 'toggle-icon dashicons dashicons-arrow-down-alt2');
}
});
// updating htaccess
$('#siteseo_htaccess_btn').on('click', function(){
event.preventDefault();
let spinner = $(event.target).next('.spinner');
if(spinner.length){
spinner.addClass('is-active');
}
let htaccess_code = $('#siteseo_htaccess_file').val(),
htaccess_enable = $('#siteseo_htaccess_enable').is(':checked') ? 1 : 0;
$.ajax({
url : siteseo_pro.ajax_url,
method: 'POST',
data: {
action: 'siteseo_pro_update_htaccess',
htaccess_code: htaccess_code,
htaccess_enable: htaccess_enable,
_ajax_nonce : siteseo_pro.nonce
},
success: function(res){
if(spinner.length){
spinner.removeClass('is-active');
}
if(res.success){
alert(res.data);
return;
}
if(res.data){
alert(res.data)
return;
}
alert('Something went wrong, updating the file');
}
});
});
// Csv download
$('#siteseo-export-csv').on('click', function(event){
event.preventDefault();
$.ajax({
method: 'POST',
url: siteseo_pro.ajax_url,
data: {
action: 'siteseo_pro_export_redirect_csv',
_ajax_nonce: siteseo_pro.nonce
},
beforeSend: function(){
$('#siteseo-export-csv').prop('disabled', true);
},
xhrFields:{
responseType: 'blob'
},
success: function(response, status, xhr){
var filename = 'siteseo-redirect-data-' + new Date().toISOString().slice(0,10) + '.csv';
var disposition = xhr.getResponseHeader('Content-Disposition');
if(disposition){
var match = disposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
if(match && match[1]){
filename = match[1].replace(/['"]/g, '');
}
}
var blob = new Blob([response], { type: 'text/csv' });
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
},
error: function(){
alert('Error connecting to the server');
},
complete: function(){
$('#siteseo-export-csv').prop('disabled', false);
}
});
});
// Clear all redirect logs
$('#siteseo_redirect_all_logs').on('click', function(){
event.preventDefault();
if(!confirm('Are you sure you want to clear all logs?')){
return;
}
let spinner = $(event.target).next('.spinner');
if(spinner.length){
spinner.addClass('is-active');
}
$.ajax({
method: 'POST',
url: siteseo_pro.ajax_url,
data: {
action: 'siteseo_pro_clear_all_logs',
_ajax_nonce: siteseo_pro.nonce
},
success: function(res){
if(spinner.length){
spinner.removeClass('is-active');
}
if(res.success){
alert(res.data);
window.location.reload();
return;
}
alert('Unable to clear logs.');
},
error: function(){
alert('Error clearing logs.');
if(spinner.length){
spinner.removeClass('is-active');
}
}
});
});
// update robots file
$('#siteseo-update-robots').on('click', function(){
event.preventDefault();
let spinner = $(event.target).next('.spinner');
if(spinner.length){
spinner.addClass('is-active');
}
$.ajax({
method : 'POST',
url : siteseo_pro.ajax_url,
data : {
action : 'siteseo_pro_update_robots',
robots : $('#siteseo_robots_file_content').val(),
_ajax_nonce : siteseo_pro.nonce
},
success: function(res){
if(spinner.length){
spinner.removeClass('is-active');
}
if(res.success){
alert(res.data);
window.location.reload();
return;
}
if(res.data){
alert(res.data);
return;
}
alert('Unable to create the robots.txt file');
}
});
});
$('#select-all-logs').on('click', function(){
$('.log-selector').prop('checked', this.checked);
});
// Delete specific recoder
$('#siteseo-remove-selected-log').on('click', function(){
var selectedIds = [];
$('.log-selector:checked').each(function(){
selectedIds.push($(this).val());
});
if(selectedIds.length === 0){
alert('Please select at least one log to delete');
return;
}
if(!confirm('Are you sure you want to delete the selected logs?')){
return;
}
$.ajax({
type : 'POST',
url: siteseo_pro.ajax_url,
data:{
action: 'siteseo_pro_remove_selected_logs',
ids: selectedIds,
_ajax_nonce: siteseo_pro.nonce
},
success: function(response){
if(response.success){
$('.log-selector:checked').closest('tr').remove();
alert('Selected logs deleted successfully');
}else{
alert('Error: ' + response.data);
}
},
error: function(){
alert('Failed to delete logs. Please try again.');
}
});
});
// Delete robots txt file
$('#siteseopro-delete-robots-txt').on('click', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: siteseo_pro.ajax_url,
data: {
action: 'siteseo_pro_delete_robots_txt',
_ajax_nonce: siteseo_pro.nonce
},
success: function(response){
if(response.success){
window.location.reload();
} else{
alert(response.data);
}
},
error: function(xhr, status, error){
alert('An error occurred: ' + error);
}
});
});
// handel ajax toggle
$('.siteseo-toggleSw').on('click', function(){
const $toggle = $(this);
const toggleKey = $toggle.data('toggle-key');
const action = $toggle.data('action');
saveToggle($toggle, toggleKey, action);
});
function saveToggle($toggle, toggleKey, action){
const $container = $toggle.closest('.siteseo-toggleCnt');
const $stateText = $container.find(`.toggle_state_${toggleKey}`);
const $input = $(`#${toggleKey}`);
$container.addClass('loading');
$toggle.toggleClass('active');
const newValue = $toggle.hasClass('active') ? '1' : '0';
$input.val(newValue);
$stateText.text($toggle.hasClass('active') ? 'Click to disable this feature' : 'Click to enable this feature');
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: action,
toggle_value: newValue,
nonce: $toggle.data('nonce')
},
success: function(response){
if(response.success){
// Show the custom toast message
ToastMsg('Your settings have been saved.');
if(response.data.reload){
location.reload();
}
} else{
console.error('Failed to save toggle state');
toggleError($toggle, $input, $stateText);
ToastMsg(response.data.message || 'Failed to save toggle state', 'error');
}
},
error: function() {
console.error('Ajax request failed');
toggleError($toggle, $input, $stateText);
ToastMsg('Unable to save settings', 'error');
},
complete: function() {
$container.removeClass('loading');
}
});
}
//toast
function ToastMsg(message, type = 'success') {
const toast = $('
')
.addClass('siteseo-toast')
.addClass(type)
.html(`
${message}`);
$('body').append(toast);
// 3 seconds
toast.fadeIn(300).delay(3000).fadeOut(300, function () {
toast.remove();
});
}
// error handler
function toggleError($toggle, $input, $stateText) {
$toggle.toggleClass('active');
$input.val($toggle.hasClass('active') ? '1' : '0');
$stateText.text($toggle.hasClass('active') ? 'Disable' : 'Enable');
}
// media uploader for image logo
$('#siteseopro_structured_data_upload_img').click(function(e) {
var mediaUploader;
e.preventDefault();
if (mediaUploader) {
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Media',
button: {
text: 'Select'
},
multiple: false
});
mediaUploader.on('select', function() {
var attachment = mediaUploader.state().get('selection').first().toJSON();
$('#structured_data_image_url').val(attachment.url);
});
mediaUploader.open();
});
// media uploader for podcast image
$('#siteseo_pro_podcast_img_btn').click(function(e){
var mediaUploader;
e.preventDefault();
if(mediaUploader){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Media',
button: {
text: 'Select'
},
multiple: false
});
mediaUploader.on('select', function() {
var attachment = mediaUploader.state().get('selection').first().toJSON();
$('#siteseo_pro_podcast_img_url').val(attachment.url);
$('#siteseo_pro_podcast_img').attr('src', attachment.url);//preview
});
mediaUploader.open();
});
//Podcast Image preview
$('#siteseo_pro_podcast_img_url').on('input change', function(e){
$(this).closest('td').find('img').attr('src', $(this).val());
});
$('#siteseo-sidebar-refersh-tokens').on('click', function(e){
e.preventDefault();
let token_container = $(this).closest(".siteseo-ai-token-count");
$('.siteseo-sidebar-ai-tokens').fadeOut(200).fadeIn(200);
$.ajax({
url: siteseo_pro.ajax_url,
method: "POST",
data: {
action: "siteseo_pro_refresh_tokens",
nonce: siteseo_pro.nonce,
},
success: function(res){
if(!res.success){
if(res.data){
alert(res.data);
return;
}
alert("Something went wrong fetching token data");
return;
}
update_dashbord_ai_tokens(res.data);
},
error: function(){
alert("Error refreshing tokens");
}
});
});
function update_dashbord_ai_tokens(remaining_tokens){
let formatted_tokens = remaining_tokens < 0 ? 0 : parseInt(remaining_tokens).toLocaleString('en'),
token_badge = $('.siteseo-ai-token-badge');
// Update the tokens count text
$('.siteseo-sidebar-ai-tokens').text('Tokens Remaining ' + formatted_tokens);
// If you want to add a badge (though it's not in your original HTML)
if(token_badge.length === 0){
$('.siteseo-ai-token-count').prepend(
'
' + formatted_tokens + ' '
);
} else{
token_badge.text(formatted_tokens);
}
}
/** global schema modal **/
$('#siteseo-auto-schema-modal').dialog({
autoOpen: false,
modal: true,
width: '40%',
minWidth: 500,
maxWidth: 600,
closeOnEscape: false,
dialogClass: 'siteseo-modal',
draggable: false,
resizable: false,
position: { my: "center", at: "center", of: window },
buttons: {
"submit": {
text: "Save",
class: "save-schema-btn",
click: function(){
save_schema();
}
}
},
open: function(){
// add spinner in footer
let $btn = $(this).parent().find('.save-schema-btn');
if(!$btn.next('.spinner').length){
$btn.after('
');
}
}
});
/** Add events **/
$('#siteseo-auto-schema-modal').on('dialogopen', function() {
// Add schema rule event
$('.siteseo-add-schema-rule').off('click').on('click', function(e){
e.preventDefault();
let $row = $(this).closest('tr'),
$container = $row.find('.siteseo-schema-rule-container'),
$first = $container.find('select').first();
let $clone = $first.clone();
let $wrapper = $('
');
$wrapper.append($clone);
$wrapper.append('
');
$container.append($wrapper);
// delete rule event as new elements are added
bind_remove_rule();
});
// Delete rule event
bind_remove_rule();
// Specific targets change event
bind_specific_targets_change();
});
$('#siteseo-auto-schema').on('click', function(e){
e.preventDefault();
// Open modal
$('#siteseo-auto-schema-modal').dialog('open');
// Clear all inputs and selects
$('input[name="schema_id"]').val('');
$('input[name="schema_name"]').val('');
$('select[name="schema_type"]').val('None').trigger('change');
// Clear dynamically added rules
$('.siteseo-schema-rule-container').each(function(){
let $first = $(this).find('select').first().clone();
$(this).empty().append($first);
});
$('.siteseo-specific-input').remove();
// Clear schema properties container
$('#siteseo-schema-properties-show').empty();
// Set modal title
$('#siteseo-auto-schema-modal').dialog('option', 'title', 'Add Schema');
});
$('#siteseo-auto-schema-import-btn').on('click', function(e){
e.preventDefault();
// Open modal
$('#siteseo-auto-schema-modal-import').dialog('open');
});
// Schema import modal
$('#siteseo-auto-schema-modal-import').dialog({
autoOpen: false,
modal: true,
width: '40%',
minWidth: 400,
maxWidth: 600,
closeOnEscape: false,
dialogClass: 'siteseo-modal',
draggable: false,
resizable: false,
position: { my: "center", at: "center", of: window },
buttons: {
"submit": {
text: 'Import',
class: "schema-import-btn",
click: function(){
import_schema();
}
}
},
open: function(){
var $btn = $(this).parent().find('.schema-import-btn');
if(!$btn.next('.spinner').length){
$btn.after('
');
}
}
});
// Schema URl fetch
function import_schema(){
var spinner = $('.schema-import-btn').next('.spinner');
if(spinner.length){
spinner.addClass('is-active');
}
$.ajax({
url: siteseo_pro.ajax_url,
type: 'POST',
data: {
action: 'siteseo_import_schema',
type: $('#siteseo-select-control-select').val(),
url: $('#siteseo-text-control-url').val(),
html: $('#siteseo-textarea-control-html').val(),
json: $('#siteseo-textarea-control-json').val(),
is_manual : $('#siteseo-schama-import-manual').is(':checked') ? true : '',
nonce: siteseo_pro.nonce
},
success: function(response){
if(spinner.length){
spinner.removeClass('is-active');
}
if(response.success){
render_schema_list(response.data.schemas);
}else{
alert(response.data);
}
}
});
}
// Schema Show in UI
function render_schema_list(schemas){
// Reset previous data
$('#siteseo-schemas-list').html('');
schemas.forEach(function(schema, index){
if(typeof highlightJson === 'function'){
var highlight = highlightJson(schema.json_ld);
}
var item = `
`;
$('#siteseo-schemas-list').append(item);
});
$('#siteseo-imported-schema-results').show();
// For Copy
$('.siteseo-copy-schema-btn').off().on('click', function(){
let id = $(this).data('target'),
text = $('#' + id).val().trim();
navigator.clipboard.writeText(text);
$(this).html('
Copied!').prop('disabled', true);
setTimeout(() => {
$(this).html('
Copy').prop('disabled', false);
}, 2000);
});
// Google rich results test
$(document).on('click', '.siteseo-schema-test-btn', function(e){
e.preventDefault();
// Fetch Schema
let $wrapper = $(this).closest('.siteseo-schema'),
$textarea = $wrapper.find('.siteseo-schema-preview'),
schemaContent = $textarea.val().trim(),
$form = $('