Retrieve the first and last post in WordPress

1 minute read

The simplest web-comics navigation could work just as the WordPress default post navigation. It would just show links to the previous and to the next comic. However, webcomics often have additional navigation links to the first, last, current or latest comic. Sometimes a random link is added. Most webcomics have a similar setup, owing to the scarcity of choice in themes and plugins, but also because that makes sense. Another usual setting is that comics episodes show up in reverse chronology, latest episode first. That is the default WordPress blog post structure as well, but you might want to change that.

Retrieve the first and last post

Anyway. To design a navigation bar for comics or webcomics in WordPress, you can build on existing variables, such as $first and $next. Assuming you have a custom post type “comic” in function.php, this code would retrieve the first and last comic custom post. Fine if you have only one story, it still needs improvement to sort comics by categories and enable series.

	/**
	* Get the first and latest post link for CPT comic
	*/
	/**
	function first_comic_post() {

	// Query the database for the oldest post
	$first_comic = new WP_Query( array(
	'post_type' => 'comic',
	'post_per_page' =>1,
	'order'   => 'ASC',
	)
	);

	if ($first_comic->have_posts()) {

    $first_comic->the_post();
    $first_url=get_permalink();
    echo $first_url;
	}      

	wp_reset_postdata();
	}
	/*
	for latest post link
	*/

	/**
	function latest_comic_post( $query ) {

	// Query the database for the most recent post
	$last_comic = new WP_Query( array(
	'post_type' => 'comic',
	'showposts'=>1
	)    
	);
	if ($last_comic->have_posts()) {

    $last_comic->the_post();
    $latest_url=get_permalink();
    echo $latest_url;
	}

	wp_reset_postdata();
	}

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...