Deutsch
Due to the popularity of my earlier article about creating a WordPress Sitemap without a Plugin and my growing familiarity with the WordPress core, I decided to introduce another possibility. With this one, there are no custom database queries necessary, it solely depends on already existing WordPress functions:
/** * Builds the Sitemap and echoes the HTML * * @echo Sitemap */ function sitemap() { $category_array = get_categories(array( 'exclude_tree' => 24 )); $sitemap = "<h3>" . __( 'Posts','domain' ) . "</h3><ul>"; foreach ( $category_array as $category ) { $sitemap .= "<li>".__('Category: ', 'domain').'<a href="'.get_category_link($category->cat_ID).'" title="' . sprintf( __( "View all posts in %s" , 'domain'), $category->name ) . '">'.$category->name."</a><ul>n"; $post_array = get_posts(array( 'post_type' => 'post', 'cat' => $category->cat_ID )); foreach ( $post_array as $post ) { $post->post_title = apply_filters( 'the_title', $post->post_title, $post->ID ); $sitemap .= "<li><a href="" . get_permalink($post->ID) . '" title="' . esc_attr($post->post_title) . '">' . $post->post_title . "</a></li>"; } $sitemap .= "</ul>"; } $sitemap .= "</li></ul>"; $sitemap .= "<h3>" . __( 'Pages','domain' ) . "</h3><ul>"; $sitemap .= wp_list_pages(array( 'echo' => false, 'title_li' => false, 'exclude' => '343,487,491' ))."</ul>"; echo $sitemap; }
The first function obviously grabs all the category objects from the database. This function has a number of possibilites to customize – read about them in the WordPress Codex.
$category_array = get_categories(array( 'exclude_tree' => 24 ));
Next, wie go through the categorie objects and fetch the associated posts. Now we can build the unordered list. I slotted the “the_title” filter ahead of the link, to give my plugins the opportunity to work their magic.
foreach($category_array as $category){ $sitemap .= "<li>" . __('Category: ', 'domain') . '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '">' . $category->name . "</a><ul>"; $post_array = get_posts(array( 'post_type' => 'post', 'cat' => $category->cat_ID )); foreach ( $post_array as $post ) { $post->post_title = apply_filters( 'the_title', $post->post_title, $post->ID ); $sitemap .= '<li><a href="' . get_permalink($post->ID) . '" title="' . esc_attr($post->post_title) . '">' . $post->post_title . '</a></li>'; } $sitemap .= "</ul>"; }
And after all posts have been taken care of, there are only the pages missing (ich exluded the footer pages to only display pages with relevant content):
$sitemap .= wp_list_pages(array( 'echo' => false, 'title_li' => false, 'exclude' => '343,487,491' ))."</ul>";
That’s all there is to it!