Support » Themes and Templates » How to detect current archive page

  • Spamboy

    (@spamboy)


    I am trying to code my archive pages to show different HTML depending on what page of the archive you are on.

    For example, if you were to view the archive “Family News”, the first page URL might look something like this:

    http://www.example.com/category/family_news/

    Clicking on the “next page” link would take you to:

    http://www.example.com/category/family_news/page/2/

    What PHP code would allow me to detect if I am on the first page of an archive?

    Some information about my setup: Under Options > Reading, I setup my blog to “Show at Most 1 Posts”. I am using the default archive template (archive.php) with one exception — I added the following line of code before The Loop to sort my posts by date ascending:

    <?php $posts = query_posts($query_string . '&orderby=post_date&order=asc'); ?>

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter Spamboy

    (@spamboy)

    Although it’s not a solution provided by calling a delivered function, digging around the link-template.php file gave me the means to a homegrown solution.

    I grabbed snippets of OOTB code and came up with this:

    <?php
    $sb_min_page = intval($wp_query->min_num_pages);
    $sb_max_page = intval($wp_query->max_num_pages);
    $sb_cur_page = intval($paged);
    ?>

    Then, at the beginning of my category archive I had the following code, which either will show a link to the previous page (if on a page above Page 1), or a placeholder for a link to the previous category (once I code it):

    <?php if ($sb_cur_page == $sb_min_page) {
    	echo "GO TO PREVIOUS CATEGORY";
    } else { ?>
    	<?php previous_posts_link('Previous Page') ?></div>
    <?php } ?>

    If anyone has a cleaner solution, I’m down with that.

    You can simply use
    if ($paged < 2)

    Lots more information here.

    aaahhhhhhhhhh yessss:

    $sb_max_page = intval($wp_query->max_num_pages);

    That is brilliant. I was wanting to format the area of the prev / next links but in a way that I needed to know in advance if there were more pages. This is perfect!

    It lets me have a well behaved and informative navigation at the end of the page. 🙂

    $sb_max_page = intval($wp_query->max_num_pages);
    if( $sb_max_page > 1 ) {
    	?>
    	<span id="red-box" style="text-align:center">
    	<?php
    	previous_posts_link('&laquo; Newer Entries');
    	if( $paged > 1 ) {
    		echo " - Page $paged of $sb_max_page";
    		// will be true if we have a "full" page of posts:
    		if ( $wp_query->post_count == get_option('posts_per_page') ) {
    		echo " - ";
    		}
    	}
    	if( $paged == '') {
    		echo "Page 1 of $sb_max_page ";
    	}
    	next_posts_link('Older Entries &raquo;'); 
    
    	?>	</span><P></p> <?
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to detect current archive page’ is closed to new replies.