Having ChatGPT write a Sitemap

blog cover image
17
3.7K followers
Updated

I asked ChatGPT to write some Sitemap code in php for one of my websites. This has 240+ posts and 140+ products on it.

I of course trialed it on a test site to make sure it worked before going live.

It took several iterations to get to where I wanted it to be. My site has Pages, Posts and Products, so I needed them all included, itemised and paginated. Here's my interaction with ChatGPT.

My original request was:

Me: "Can you write me some code to produce a site map in Wordpress that can be displayed on a page by using a shortcode. Please tell me which Wordpress file to insert the code into".

Then it needed several modifications to get to where I needed it. I won't provide the output after each prompt, but the finished code is at the end.

Me: "Modify the code to prevent the sitemap page itself being listed in the page where the shortcode is displayed"

Me: "Can you please modify the code to include posts as well as pages and segregate them with suitable headings"

Me: "This seems to only list 5 posts. Can you modify it to include all posts please?"

Me: "Please paginate the results"

Me: "Please format the pagination links to display all numbered pages by default"

Me: "Don't show it as a list!"

Me: "Can you recode so the pages only appear on page 1 rather than all of the pages?"

Me: "This doesn't work. The pages don't appear on the first page"

Me: "That works well. Can you include Products to the index as well please?"

Me: "Ok, this time only the pages and products show in the sitemap. You need to include the posts"

Me: "Thanks but that's still not quite right. The pagination needs to be at the end of the pages, posts and products map overall, not after each section. Can you correct that?"

ChatGPT eventually came up with the finished code, which can be seen in action here.

https://durhamukweather.com/sitemap-page/

It's very impressive that ChatGPT can produce such code, though it's important to test, test and test again to make sure everything works correctly.

If you do make changes to your Theme code, make sure to create a Child theme and make the changes there, so any core update to Wordpress doesn't overwrite the changes you made.

Has anyone had ChatGPT write code for your site? What did you do?

Happy ChatGPT-ing. 😎

Dave.

Finished Code (for reference)

// Create a shortcode to display the site map

function custom_sitemap_shortcode() {

// Get the current page ID

global $post;

$current_page_id = $post->ID;

$output = '<h2>Site Map</h2>';

// Determine if it's the first page

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$is_first_page = ($paged == 1);

// Store the sections in an array

$sections = array();

// Display pages only on the first page

if ($is_first_page) {

$pages_section = '<h3>Pages</h3>';

$pages_section .= '<ul>';

// Get all published pages excluding the current page

$pages = get_pages(array(

'exclude' => $current_page_id // Exclude the current page

));

foreach ($pages as $page) {

$pages_section .= '<li><a href="' . get_permalink($page->ID) . '">' . $page->post_title . '</a></li>';

}

$pages_section .= '</ul>';

$sections[] = $pages_section;

}

// Display posts

$posts_section = '<h3>Posts</h3>';

$posts_section .= '<ul>';

$posts_per_page = 5; // Number of posts per page

$args_posts = array(

'post_type' => 'post',

'post_status' => 'publish',

'posts_per_page' => $posts_per_page,

'paged' => $paged // Pagination parameter

);

$posts_query = new WP_Query($args_posts);

if ($posts_query->have_posts()) {

while ($posts_query->have_posts()) {

$posts_query->the_post();

$posts_section .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';

}

}

$posts_section .= '</ul>';

$sections[] = $posts_section;

// Display products

$products_section = '<h3>Products</h3>';

$products_section .= '<ul>';

$products_per_page = 5; // Number of products per page

$args_products = array(

'post_type' => 'product',

'post_status' => 'publish',

'posts_per_page' => $products_per_page,

'paged' => $paged // Pagination parameter

);

$products_query = new WP_Query($args_products);

if ($products_query->have_posts()) {

while ($products_query->have_posts()) {

$products_query->the_post();

$products_section .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';

}

}

$products_section .= '</ul>';

$sections[] = $products_section;

// Combine all sections

$output .= implode('', $sections);

// Pagination links

$output .= '<div class="pagination">';

$output .= paginate_links(array(

'total' => max($posts_query->max_num_pages, $products_query->max_num_pages),

'current' => $paged,

'prev_text' => __('« Previous'),

'next_text' => __('Next »'),

'mid_size' => -1, // Show all numbered pages

));

$output .= '</div>';

// Reset post data

wp_reset_postdata();

return $output;

}

add_shortcode('sitemap', 'custom_sitemap_shortcode');

Login
Create Your Free Wealthy Affiliate Account Today!
icon
4-Steps to Success Class
icon
One Profit Ready Website
icon
Market Research & Analysis Tools
icon
Millionaire Mentorship
icon
Core “Business Start Up” Training

Recent Comments

21

Cool. I always wondered how to do that. Looks like you were able to get it after a lot of trial and error.

Hope you have a great weekend with beautiful weather!

Karin

Yes, we got there in the end. ChatGPT very rarely gets it exactly as you want it first time, but it 'remembers' what it's done so far and is capable of making tweaks.

Dave

This is great.

Thanks Dave

Steve

Interesting information, Dave!

Jeff

I’m loving it, Dave! 👍👍😎

Let us know if you see an indexing improvement in GSC.

Frank 🎸

It all helps Frank 😎

Sold a weather station from the site yesterday, but I don't think I can attribute it to this. 😂

Dave

Keep on Rockin’ it with AI, Dave! 😎

Frank 🎸

I asked ChatGPT for other ideas:

There are many things I can help you create in WordPress using code. Here are a few examples:

1. **Custom Post Types**: You can create custom post types to organize different types of content on your WordPress site. For example, if you have a portfolio section, you can create a custom post type called "Portfolio" to manage portfolio items separately from regular posts.

2. **Custom Taxonomies**: Taxonomies allow you to group and organize your content in WordPress. You can create custom taxonomies to categorize your content in different ways. For example, if you have a recipe website, you can create custom taxonomies like "Cuisine" or "Difficulty Level" to categorize recipes.

3. **Custom Fields**: Custom fields allow you to add additional metadata to your posts and pages. You can use custom fields to store and display extra information about your content. For example, if you have a real estate website, you can add custom fields for property features like "Number of Bedrooms" or "Square Footage".

4. **Shortcodes**: Shortcodes allow you to create reusable pieces of code that can be inserted into your posts, pages, or widgets to display dynamic content. You can create custom shortcodes to add functionality or display specific information on your site.

5. **Custom Widgets**: Widgets are small blocks of content that can be added to widgetized areas in your WordPress theme, such as sidebars or footers. You can create custom widgets to add new functionality or display custom content in these areas.

6. **Custom Page Templates**: Page templates allow you to create different layouts for your pages in WordPress. You can create custom page templates to apply unique designs or functionality to specific pages on your site.

7. **Custom Plugins**: If you need more complex functionality that isn't available through themes or built-in WordPress features, you can create custom plugins. Plugins allow you to extend the functionality of WordPress by adding new features or modifying existing ones.

8. **Theme Customization**: If you have a specific design in mind for your website, you can customize your WordPress theme by modifying the theme files or adding custom CSS styles.

These are just a few examples of what you can create in WordPress using code. If you have any specific requirements or ideas for your website, feel free to let me know, and I can provide more tailored assistance!

That definitely an AI-generated copy lololol 🤔

So is that lolololol.

StevoiAI

Complex Code

---
def save_data(self, file_path):
try:
with open(file_path, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'Grade/Subject'])

for student in self.students:
writer.writerow([student.name, student.age, student.grade])

for teacher in self.teachers:
writer.writerow([teacher.name, teacher.age, teacher.subject])

print("Data saved successfully.")
except IOError as e:
print(f"Error saving data: {e}")

What does that particular code do?

Dave

lol, all code is complex for Teachers, especially ESL school owners. Double lol
Stevoi

Emm lemme think lol I know one thing for sure, it is in Python :)

:)

Whaaat a pants python...whoops ...no..Gotcha...lol.

Pants is a fast, scalable, and user-friendly build system for codebases of all sizes. It's currently focused on Python, Go, Java, Scala, Kotlin, Shell, and Docker :)

As well as Jock and Strap…
Stevoi

See more comments

Login
Create Your Free Wealthy Affiliate Account Today!
icon
4-Steps to Success Class
icon
One Profit Ready Website
icon
Market Research & Analysis Tools
icon
Millionaire Mentorship
icon
Core “Business Start Up” Training