Quantcast
Channel: Topic Tag: MySQL | WordPress.org
Viewing all articles
Browse latest Browse all 5530

su1 on "Display a sitemap inside a post - mysql query?"

$
0
0

Hello,

I'm trying to display a custom sitemap inside a post, with a tag [sitemap] calling a custom function sitemap_f() in my functions.php file.

What I want to achieve is just retrieve say 30 random already-published posts, and display them in a post as a sitemap, so just a list with the title of the posts and a link to the posts.

I've tried to tweak a piece of code found on the web and it works, but because it was meant to create a sitemap sorted by date, it's much more complicated than what I'd like and I can't simplify it without breaking it.

My code is the following, how would you make it simpler to achieve what I want to do? Thanks.

function sitemap_f( $atts ) {

	global $month, $wpdb, $wp_version;

	// a mysql query to get the list of distinct years and months that posts have been created
	$sql = 'SELECT
			DISTINCT YEAR(post_date) AS year,
			MONTH(post_date) AS month,
			count(ID) as posts
		FROM ' . $wpdb->posts . '
		WHERE post_status="publish"

		GROUP BY YEAR(post_date),
			MONTH(post_date)
		ORDER BY RAND()';

	// use get_results to do a query directly on the database
	$archiveSummary = $wpdb->get_results($sql);
	$posts_affiches=0;
	$casse=0;
	$nombre_posts = 500;
	// if there are any posts
	if ($archiveSummary) {
		// loop through the posts
		foreach ($archiveSummary as $date) {
			// reset the query variable
			unset ($bmWp);
			// create a new query variable for the current month and year combination
			$bmWp = new WP_Query('year=' . $date->year . '&monthnum=' . zeroise($date->month, 2) . '&posts_per_page=-1');

			// if there are any posts for that month display them
			if ($bmWp->have_posts()) {
				// display the archives heading
				$url = get_month_link($date->year, $date->month);
				$text = $month[zeroise($date->month, 2)] . ' ' . $date->year;

				echo get_archives_link($url, $text, '', '<h3>', '</h3>');
				echo '<ul class="postspermonth">';

				// display an unordered list of posts for the current month
				while ($bmWp->have_posts()) {
					$bmWp->the_post();
					echo '<li><a href="' . get_permalink($bmWp->post) . '" title="' . wp_specialchars($text, 1) . '">' . wptexturize($bmWp->post->post_title) . '</a></li>';
					$posts_affiches += 1;
					if ($posts_affiches == $nombre_posts) {
						$casse = 1;
						break;
					}
				}

				if ($casse == 1) {
					break;
				}

				echo '</ul>';
			}
		}
	}

}
add_shortcode( 'sitemap', 'sitemap_f' );

Viewing all articles
Browse latest Browse all 5530

Trending Articles