I am still in dark clouds, and I am not sure how to fetch the updated contents continuously without refreshing my sitemap. In my current code, I still need to reload the page to get the updated contents. Please help me with that I already tried to review the other questions that are similar to mine but are not useful to me.
So I have this code, I want to get the updated contents in my sitemap without refreshing the page, I used ajax but it still does not resolve the problem
SiteMapController.php
public function register()
{
// Add hook to generate sitemap on tfaf_site_map update
add_action('update_option_tfaf_site_map', array($this, 'generateSitemap'), 10, 2);
add_action('update_option_tfaf_site_map', array($this, 'generateCategorySitemap'), 10, 2);
// Add action to generate sitemap on 'generate_sitemap' action
add_action('admin_post_generate_sitemap', array($this, 'handleSitemapGeneration'));
// Register AJAX handlers for logged-in and logged-out users
add_action('wp_ajax_nopriv_get_forum_sitemap', [$this, 'handleForumSitemapAjax']);
add_action('wp_ajax_get_forum_sitemap', [$this, 'handleForumSitemapAjax']);
add_action('wp_ajax_nopriv_get_category_sitemap', [$this, 'handleCategorySitemapAjax']);
add_action('wp_ajax_get_category_sitemap', [$this, 'handleCategorySitemapAjax']);
// Hook to schedule the single event on plugin activation
add_action('init', array($this, 'scheduleSitemapCheck'));
// Hook the sitemap generation to the custom action
add_action('tfaf_generate_sitemap_event', array($this, 'maybeGenerateSitemap'));
}
// Generate topic sitemap based on trigger
public function generateSitemap()
{
error_log('generateSitemap called.');
global $wpdb;
// Fetch and unserialize the asgarosforum_options from wp_options
$asgarosforumOptionsSerialized = $wpdb->get_var("SELECT option_value FROM {$wpdb->prefix}options WHERE option_name = 'asgarosforum_options'");
$asgarosforumOptions = unserialize($asgarosforumOptionsSerialized);
// Get the posts_per_page value
$postsPerPage = isset($asgarosforumOptions['posts_per_page']) ? absint($asgarosforumOptions['posts_per_page']) : 10;
if ($postsPerPage <= 0) {
$postsPerPage = 10; // Fallback to a default value of 10
}
$forums = $wpdb->get_results("SELECT id FROM {$wpdb->prefix}forum_forums");
$sitemapIndex = 1;
$urlCount = 0;
$maxUrlsPerSitemap = 1000;
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
foreach ($forums as $forum) {
$topics = $wpdb->get_results($wpdb->prepare("SELECT id, parent_id, author_id, slug, name FROM {$wpdb->prefix}forum_topics WHERE parent_id = %d", $forum->id));
foreach ($topics as $topic) {
$totalPosts = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}forum_posts WHERE parent_id = %d", $topic->id));
$totalPages = ceil($totalPosts / $postsPerPage);
for ($page = 1; $page <= $totalPages; $page++) {
$url = home_url('/forum/topic/' . $topic->slug);
if ($page > 1) {
$url .= '/?part=' . $page;
}
$last_post_date = $wpdb->get_var($wpdb->prepare("
SELECT
CASE
WHEN MAX(date_edit) = '1000-01-01' THEN MAX(date)
ELSE MAX(date_edit)
END as last_post_date
FROM {$wpdb->prefix}forum_posts
WHERE parent_id = %d", $topic->id));
$urlElement = $xml->addChild('url');
$urlElement->addChild('loc', $url);
$urlElement->addChild('lastmod', date(DATE_W3C, strtotime($last_post_date)));
$urlCount++;
if ($urlCount >= $maxUrlsPerSitemap) {
$this->saveXmlToTransient($xml, $sitemapIndex);
$sitemapIndex++;
$urlCount = 0;
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
}
}
}
}
if ($urlCount > 0) {
$this->saveXmlToTransient($xml, $sitemapIndex);
}
}
private function saveXmlToTransient($xml, $index)
{
$xmlContent = $xml->asXML();
$transformedXml = $this->customTransformXmlForum($xmlContent);
// Log saving of transient
error_log("Saving XML to transient with index: $index");
set_transient("sitemap_forum_{$index}", $transformedXml, 24 * HOUR_IN_SECONDS);
}
// Generate category sitemap based on trigger
public function generateCategorySitemap()
{
error_log('generateCategorySitemap called.');
global $wpdb, $asgarosforum;
$categories = $asgarosforum->content->get_categories(false);
$category_names = [];
if ($categories) {
foreach ($categories as $category) {
$category_names[$category->term_id] = $category->name;
}
}
if (empty($category_names)) {
error_log('No categories found.');
return;
}
$parent_ids = $wpdb->get_results("SELECT DISTINCT parent_id FROM {$wpdb->prefix}forum_forums");
if (empty($parent_ids)) {
error_log('No parent_ids found.');
return;
}
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
foreach ($parent_ids as $parent) {
if (isset($category_names[$parent->parent_id])) {
$category_name = $category_names[$parent->parent_id];
$url = home_url('/forum/' . sanitize_title($category_name));
$urlElement = $xml->addChild('url');
$urlElement->addChild('loc', $url);
} else {
error_log('Category name not found for parent_id: ' . $parent->parent_id);
}
}
$this->saveCatXmlToTransient($xml);
}
// AJAX handler for forum sitemap
public function handleForumSitemapAjax() {
$index = isset($_POST['sitemap_index']) ? intval($_POST['sitemap_index']) : 1;
$xmlContent = $this->getXmlFromTransient($index);
if ($xmlContent) {
$htmlContent = $this->customTransformXmlForum($xmlContent);
echo $htmlContent;
} else {
wp_die('Sitemap not found', 'Error', array('response' => 404));
}
wp_die(); // Required to properly terminate AJAX requests in WordPress
}
// AJAX handler for category sitemap
public function handleCategorySitemapAjax() {
$xmlContent = $this->getCatXmlFromTransient();
if ($xmlContent) {
$htmlContent = $this->customTransformXmlCategories($xmlContent);
echo $htmlContent;
} else {
wp_die('Sitemap not found', 'Error', array('response' => 404));
}
wp_die(); // Required to properly terminate AJAX requests in WordPress
}
// Function to retrieve forum sitemap XML from transient
private function getXmlFromTransient($index = 1) {
return get_transient("sitemap_forum_{$index}");
}
// Function to retrieve category sitemap XML from transient
private function getCatXmlFromTransient() {
return get_transient("sitemap_categories");
}
private function saveCatXmlToTransient($xml)
{
$xmlContent = $xml->asXML();
$transformedXml = $this->customTransformXmlCategories($xmlContent);
// Log saving of category transient
error_log("Saving category XML to transient.");
set_transient("sitemap_categories", $transformedXml, 24 * HOUR_IN_SECONDS);
}
private function customTransformXmlCategories($xmlContent)
{
$xml = new SimpleXMLElement($xmlContent);
$html = '
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Forum Category Sitemap</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="/wp-content/plugins/toolbox-for-asgaros-forum/assets/sitemap-design.css"/>
<style>
body { font-family: Helvetica, Arial, sans-serif; font-size: 13px; color: #545353; }
table { border: none; border-collapse: collapse; width: 100%; }
#sitemap tr:nth-child(odd) td { background-color: #eee !important; }
#sitemap tbody tr:hover td { background-color: #ccc; }
#sitemap tbody tr:hover td, #sitemap tbody tr:hover td a { color: #000; }
#category-sitemap-container { margin: 0 auto; width: 1000px; }
.expl { margin: 18px 3px; line-height: 1.2em; }
.expl a { color: #da3114; font-weight: 600; }
.expl a:visited { color: #da3114; }
a { color: #000; text-decoration: none; }
a:visited { color: #777; }
a:hover { text-decoration: underline; }
td { font-size:13px; }
th { text-align:left; padding-right:30px; font-size:11px; }
thead th { border-bottom: 1px solid #000; }
</style>
</head>
<body>
<div id="category-sitemap-container">
<h1>Forum Category Sitemap</h1>
<p class="expl">
This is an XML Sitemap designed to increase forum content indexing speed.<br/>
Generated by Toolbox for Asgaros Forum for search engines. More information on <a href="https://www.sitemaps.org/">sitemaps.org</a>.<br/>
This sitemap contains ' . $xml->count() . ' categories.<br/>
</p>
<table id="sitemap" cellpadding="3">
<thead>
<tr>
<th width="100%">URL</th>
</tr>
</thead>
<tbody>';
foreach ($xml->url as $url) {
$html .= '<tr>
<td><a href="' . htmlspecialchars($url->loc) . '">' . htmlspecialchars($url->loc) . '</a></td>
</tr>';
}
$html .= '
</tbody>
</table>
</div>
</body>
</html>';
return $html;
}
private function customTransformXmlForum($xmlContent)
{
$xml = new SimpleXMLElement($xmlContent);
$html = '
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Forum Topic Sitemap</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="/wp-content/plugins/toolbox-for-asgaros-forum/assets/sitemap-design.css"/>
<style>
body { font-family: Helvetica, Arial, sans-serif; font-size: 13px; color: #545353; }
table { border: none; border-collapse: collapse; width: 100%; }
#sitemap tr:nth-child(odd) td { background-color: #eee !important; }
#sitemap tbody tr:hover td { background-color: #ccc; }
#sitemap tbody tr:hover td, #sitemap tbody tr:hover td a { color: #000; }
#forum-sitemap-container { margin: 0 auto; width: 1000px; }
.expl { margin: 18px 3px; line-height: 1.2em; }
.expl a { color: #da3114; font-weight: 600; }
.expl a:visited { color: #da3114; }
a { color: #000; text-decoration: none; }
a:visited { color: #777; }
a:hover { text-decoration: underline; }
td { font-size:13px; }
th { text-align:left; padding-right:30px; font-size:11px; }
thead th { border-bottom: 1px solid #000; }
</style>
</head>
<body>
<div id="forum-sitemap-container">
<h1>Forum Topic Sitemap</h1>
<p class="expl">
This is an XML Sitemap designed to increase forum content indexing speed.<br/>
Generated by Toolbox for Asgaros Forum for search engines. More information on <a href="https://www.sitemaps.org/">sitemaps.org</a>.<br/>
This sitemap contains ' . $xml->count() . ' topics.
</p>
<table id="sitemap" cellpadding="3">
<thead>
<tr>
<th width="75%">URL</th>
<th width="25%">Last Modified</th>
</tr>
</thead>
<tbody>';
foreach ($xml->url as $url) {
$html .= '<tr>
<td><a href="' . htmlspecialchars($url->loc) . '">' . htmlspecialchars($url->loc) . '</a></td>
<td>' . htmlspecialchars(substr($url->lastmod, 0, 10)) . '</td>
</tr>';
}
$html .= '
</tbody>
</table>
</div>
</body>
</html>';
return $html;
}
Enqueue.php
public function register()
{
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin'));
}
public function enqueue_admin()
{
// Enqueue tfaf-sitemap.js script
wp_enqueue_script('tfaf-sitemap', TFAF_PLUGIN_URL . '/assets/tfaf-sitemap.js', array('jquery'), null, true);
// Localize script to pass AJAX URL to JavaScript
wp_localize_script('myplugin-script', 'myplugin_ajax', array(
'ajax_url' => admin_url('admin-ajax.php')
));
}
tfaf-sitemap.js
jQuery(document).ready(function($) {
function updateForumSitemap() {
$.ajax({
url: myplugin_ajax.ajax_url, // Use the localized variable
type: 'POST',
data: {
action: 'get_forum_sitemap'
},
success: function(response) {
$('#forum-sitemap-container').html(response);
},
error: function(xhr, status, error) {
console.error('Error updating forum sitemap:', error);
}
});
}
function updateCategorySitemap() {
$.ajax({
url: myplugin_ajax.ajax_url, // Use the localized variable
type: 'POST',
data: {
action: 'get_category_sitemap'
},
success: function(response) {
$('#category-sitemap-container').html(response);
},
error: function(xhr, status, error) {
console.error('Error updating category sitemap:', error);
}
});
}
setInterval(function() {
updateForumSitemap();
updateCategorySitemap();
}, 5000);
updateForumSitemap();
updateCategorySitemap();
});
MooMoo_ Melody is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.