Add a post counter to each post that works with pagination

I needed to add an incrementing number to each post on an archive page within WordPress. The issue I was having was with pagination, the counter would be reset on each page.

To resolve this I had to get the posts per page and total posts and work out a formula for correctly setting my counter on each page.

$posts_per_page = get_option( 'posts_per_page' );
$total_posts = $GLOBALS['wp_query']->found_posts;
$total_pages = $posts_per_page / $total_posts;
$current_page = (get_query_var('paged')) ? get_query_var('paged') : 1;

if ( $current_page === 1 ) {
// On page 1 start at 1
$counter = 1;
} elseif ( $current_page === 2 ) {
// On page 2 start on the post per page + 1
$counter = $posts_per_page + 1;
} else {
// On other pages.
// For example on page 2 with 5 posts per page we want the counter to start on 6
// So page * posts per page - posts on the last page + 1 to get to this page = 6
$counter = ( $current_page * $posts_per_page - $posts_per_page + 1 );
} ?>

Thanks to the article for pointing me in the right direction.

Display custom post types from WordPress RSS feed as HTML

I was working on a RSS driven newsletter for a client that need to have a web page displaying all the posts from a custom post type using the WordPress RSS feed.

First I needed to get the correct feed URL. The feed URL for custom post types can be located using a query string in the URL:

Replacing the with the url of the site you will be getting the feed from. And change yourcustomposttype with the name of your custom post type.


We can then use PHP to load the feed in to an array and loop through each elements tag name and pull the values we need and echo them to the page:


$url = ''; $rss = new DOMDocument(); $rss->load($url);
$feed = array();

foreach ($rss->getElementsByTagName('item') as $node) {
  $image = $node->getElementsByTagName('image')->item(0)->nodeValue;
  $title = $node->getElementsByTagName('title')->item(0)->nodeValue;
  $link = $node->getElementsByTagName('link')->item(0)->nodeValue;

  echo '<h1><a href="' . $link . '">' . $title . '</a></h1>';

} ?>

Big thanks to this question on stack over flow and several of the answers