Skip to content

Instantly share code, notes, and snippets.

@anonaba
Last active November 24, 2024 07:58
Show Gist options
  • Select an option

  • Save anonaba/eb47fdc6ceb7ec97193a0ea758f495a4 to your computer and use it in GitHub Desktop.

Select an option

Save anonaba/eb47fdc6ceb7ec97193a0ea758f495a4 to your computer and use it in GitHub Desktop.
WP Pages

WP Pages

  • single.php
  • singular.php
  • archive.php
  • pagination

What is archive.php in WordPress?

In WordPress, archive.php is a template file used to display archive-type pages. These pages typically list posts grouped by a specific taxonomy, date, author, or other criteria. The archive.php file serves as the default template for these archive pages unless a more specific template is defined (e.g., category.php, tag.php).

What Does archive.php Do?

The archive.php file determines the layout and design for the following types of archive pages:

  1. Category archives (e.g., example.com/category/news)
  2. Tag archives (e.g., example.com/tag/tech)
  3. Author archives (e.g., example.com/author/admin)
  4. Date archives (e.g., example.com/2023/11/)
  5. Custom taxonomy archives (e.g., example.com/genre/action for a genre taxonomy)
  6. Post type archives (e.g., example.com/products for a custom post type archive)

Template Hierarchy and archive.php

WordPress uses a specific hierarchy to determine which template file to load for an archive page. If a more specific file does not exist, WordPress falls back to archive.php. For example:

  1. Category Archive

    • category-slug.php
    • category-id.php
    • category.php
    • archive.php
    • index.php
  2. Tag Archive

    • tag-slug.php
    • tag-id.php
    • tag.php
    • archive.php
    • index.php
  3. Custom Post Type Archive

    • archive-{post_type}.php (e.g., archive-products.php)
    • archive.php
    • index.php

When to Use archive.php

  • Use archive.php when you want to define a default design for all archive pages that don't have a more specific template.
  • It is a good fallback template if you don’t need unique layouts for individual archive types (categories, tags, etc.).
  • For custom post type archives, ensure the has_archive parameter is set to true when registering the custom post type.

How to Use archive.php

  1. Create or Edit the File

    • Create a file named archive.php in your theme directory if it doesn't exist.
    • Open the file for editing in a text/code editor.
  2. Basic Structure Here’s a simple example of archive.php:

    <?php get_header(); ?>
    
    <main id="main-content">
        <?php if (have_posts()) : ?>
            <header class="archive-header">
                <h1 class="archive-title">
                    <?php
                    // Display archive title
                    the_archive_title();
                    ?>
                </h1>
                <?php the_archive_description('<div class="archive-description">', '</div>'); ?>
            </header>
    
            <?php
            // Loop through posts
            while (have_posts()) : the_post(); ?>
                <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                    <div class="entry-content">
                        <?php the_excerpt(); ?>
                    </div>
                </article>
            <?php endwhile; ?>
    
            <?php
            // Pagination
            the_posts_pagination();
            ?>
        <?php else : ?>
            <p><?php _e('No posts found.', 'your-theme-text-domain'); ?></p>
        <?php endif; ?>
    </main>
    
    <?php get_sidebar(); ?>
    <?php get_footer(); ?>
  3. Customize the Layout

    • Add custom styles or markup to match your theme's design.
    • Use conditional logic (is_category(), is_tag(), etc.) to tailor the layout further.
  4. Test the Template

    • Visit an archive page on your site (e.g., a category or tag archive) to ensure the template is being applied correctly.

Tips for Using archive.php

  • Use Functions for Flexibility: Use functions like the_archive_title() and the_archive_description() to dynamically display archive-specific content.

  • Support Pagination: Include pagination using the_posts_pagination() or paginate_links().

  • Add Breadcrumbs: Enhance user navigation by including a breadcrumb trail if your theme supports it.

  • Fallback Logic: If you want to display a unique layout for certain archives but still fall back to archive.php for others, create specific templates and leave archive.php as the fallback.

By understanding the role of archive.php, you can create consistent and well-structured archive pages for your WordPress site.

What is Pagination in WordPress?

Pagination in WordPress refers to the process of dividing content (such as blog posts, search results, or archives) into multiple pages rather than displaying all items on a single page. This improves user experience by:

  1. Reducing page load time.
  2. Enhancing navigation for large content sets.
  3. Making the content more digestible.

Examples include numbered pages, "Older Posts" and "Newer Posts" links, or a "Load More" button.


When to Use Pagination

Use pagination when:

  • Your website has a large number of blog posts, products, or other content types that would overwhelm users if displayed all at once.
  • You want to improve SEO by creating separate URLs for content chunks (allowing better indexing).
  • Your design requires a structured and clean layout for better user engagement.

How to Use Pagination in WordPress

1. Pagination for Blog/Archive Pages

WordPress automatically supports pagination for posts when set up correctly. To enable or modify:

  • Go to Settings > Reading in the WordPress dashboard.
  • Set the "Blog pages show at most" value to the desired number of posts per page.

WordPress will automatically paginate posts based on this setting.


2. Custom Pagination in Templates

If you're creating a custom theme or template, use functions like the_posts_pagination() or paginate_links().

Example with the_posts_pagination():
<?php
if (have_posts()) : 
    while (have_posts()) : 
        the_post();
        // Display post content
    endwhile;
  
     // Display pagination
      the_posts_pagination();
    
    // add array of options if is needed
    // the_posts_pagination(array(
    //     'mid_size'  => 2,
    //     'prev_text' => __('« Previous', 'textdomain'),
    //     'next_text' => __('Next »', 'textdomain'),
    // ));
else :
    echo 'No posts found.';
endif;
?>

or

if (have_posts()) : 
    while (have_posts()) : 
        the_post();
        // Display post content
    endwhile;
    ?>

    <!-- Display pagination -->
    <div class="wpdevs-pagination">
        <div class="pages new">
            <?php previous_posts_link('<< Newer Posts'); ?>
        </div>
        <div class="pages old">
            <?php next_posts_link('Older Posts >>'); ?>
        </div>
    </div>

<?php
else :
    echo 'No posts found.';
endif;
?>

3. Custom Query Pagination

If you're using WP_Query for a custom query, pagination requires additional setup:

  1. Pass pagination parameters (paged) in your query.
  2. Display navigation using paginate_links().
Example:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
    'post_type' => 'post',
    'posts_per_page' => 5,
    'paged' => $paged,
);

$custom_query = new WP_Query($args);

if ($custom_query->have_posts()) :
    while ($custom_query->have_posts()) : 
        $custom_query->the_post();
        // Display post content
    endwhile;

    echo paginate_links(array(
        'total' => $custom_query->max_num_pages,
        'current' => $paged,
        'prev_text' => __('« Previous', 'textdomain'),
        'next_text' => __('Next »', 'textdomain'),
    ));
else :
    echo 'No posts found.';
endif;

// Reset post data after custom query
wp_reset_postdata();

4. Pagination for Pages (Multipage Posts)

For multipage content within a single post or page, use the <!--nextpage--> tag in the WordPress editor to split content. Then use wp_link_pages() to display navigation.

Example in Template:
<?php
wp_link_pages(array(
    'before' => '<div class="page-links">' . __('Pages:', 'textdomain'),
    'after'  => '</div>',
));
?>

5. Third-Party Plugins for Pagination

Plugins can enhance pagination functionality, adding features like infinite scroll, AJAX-based "Load More" buttons, or advanced designs. Popular plugins include:

  • WP-PageNavi: Adds more control over pagination styling.
  • Ajax Load More: Implements infinite scrolling.

Best Practices for Pagination

  1. SEO-Friendly URLs: Ensure your pagination uses consistent, clean URLs (/page/2/, /page/3/).
  2. Avoid Duplicate Content: Use the rel="prev" and rel="next" attributes in pagination links for SEO.
  3. Responsive Design: Ensure pagination works well on mobile and small screens.
  4. Test Performance: Balance the number of items per page for usability and performance.

Using pagination effectively improves both user experience and website performance.

Working with single.php template

In WordPress, single.php is a template file in a theme that is used to display a single post of a custom post type or a standard post. It provides the layout and structure for viewing the details of a single post, including its title, content, metadata, and any other elements specific to the post.

Key Points About single.php

  1. Purpose: Displays the content of individual posts.
  2. Hierarchy: WordPress uses the template hierarchy to determine which file to use for a single post. If single-{post-type}.php exists, WordPress uses it; otherwise, it falls back to single.php.
  3. Custom Post Types: If you have custom post types (e.g., product or portfolio), you can create specific templates like single-product.php or single-portfolio.php for those posts.
<?php get_header(); ?>

<div id="primary">
  <div id="main">
    <div class="container">
      <?php while (have_posts()): the_post() ?>
        <article id="post-<?php the_ID() ?>" <?php post_class() ?>>
          <header>
            <?php the_title('<h1>', '</h1>') ?>
            <div class="meta-info">
              <p>
                Posted in <?php echo get_the_date() ?>
                by <?php the_author_posts_link() ?>
              </p>
              <p>Categories: <?php the_category() ?></p>
              <p><?php the_tags() ?></p>
            </div>
          </header>
          <div class="content">
            <?php the_content() ?>
          </div>
        </article>
        <?php
          if (comments_open() || get_comments_number()) {
            comments_template();
          }
        ?>
      <?php endwhile ?>
    </div>
  </div>
</div>

<?php get_footer(); ?>

Example Use Case:

  • Default Post: For a blog post, single.php might display the title, content, author, and categories.
  • Custom Post Type (e.g., "Book"):
    • Create a single-book.php file for the "Book" custom post type.
    • Add fields like "Author," "Publisher," and "Publication Date" using WordPress meta fields.

By using single.php and its variations, you can control the layout and content display for specific types of posts in WordPress.

Working with singular.php template

When working with the singular.php template in WordPress, you are handling a template that can be used to display individual posts or pages. This file serves as a fallback template for both single post and page views if no other specific templates exist, such as single.php or page.php.

Here’s a basic outline of how you can work with singular.php:

1. Location and Structure

The singular.php template is typically located within your theme's directory:
/wp-content/themes/your-theme/singular.php.

If it doesn't exist, you can create one.

2. Basic Template Structure

Here's an example of how a simple singular.php file might look:

<?php get_header(); ?>

<main id="primary" class="site-main">

    <?php
    while ( have_posts() ) :
        the_post();

        get_template_part( 'template-parts/content', get_post_type() );

        // If comments are open or there are at least one comment, load up the comment template.
        if ( comments_open() || get_comments_number() ) :
            comments_template();
        endif;

    endwhile; // End of the loop.
    ?>

</main><!-- #main -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

3. Template Hierarchy

WordPress uses a hierarchy to determine which template to use. If there is no single.php or page.php, it will use singular.php to display single posts or pages.

4. Customization

To customize the singular.php template:

  • Custom Post Type Support: You can adjust the template to check for custom post types and load different parts based on the content type. This can be done using get_post_type() as seen in the example above.

  • Custom Layouts: Add specific layouts for different post types or use conditionals to include different templates or structures for pages versus posts.

  • Comments Section: comments_template(); is included to load the comments section if comments are enabled.

  • Custom Fields/Metadata: If you need to display custom fields or metadata, you can use get_post_meta() or the_field() (if you are using Advanced Custom Fields plugin).

<?php if ( get_post_meta( get_the_ID(), 'your_custom_meta_key', true ) ) : ?>
    <p><?php echo esc_html( get_post_meta( get_the_ID(), 'your_custom_meta_key', true ) ); ?></p>
<?php endif; ?>

5. Styling

Ensure that the content displayed by singular.php is styled properly by including your custom CSS. You can target specific elements or classes in the theme’s stylesheet (style.css) or use inline styles within the template itself.

If you're making changes or adding new functionality, consider using hooks or filters so you can maintain compatibility with theme updates.

Let me know if you need any specific help regarding the singular.php template!


what are the difference between singular.php and single.php?

In WordPress, both singular.php and single.php are template files used to display individual content, but they serve slightly different purposes in the template hierarchy:

  1. single.php:

    • This template is specifically for displaying individual posts of the 'post' post type (i.e., regular blog posts). It is used when a single post is viewed on the front end.
    • If WordPress detects that you are viewing a single post (like a blog post), it will look for single.php in the theme directory. If single.php doesn't exist, WordPress will fall back to other templates in the hierarchy.
  2. singular.php:

    • This is a more general template used to display any singular content, whether it's a post, page, or any other custom post type.
    • WordPress will use singular.php as a fallback if a specific template like single.php or page.php doesn't exist for that particular content type.
    • In essence, singular.php acts as a universal template for individual pieces of content that are not archive or list-based.

Template Hierarchy Order:

When WordPress tries to display a single post, it looks for templates in this order:

  1. single-{post-type}.php (for custom post types)
  2. single.php
  3. singular.php
  4. index.php

When it tries to display a page:

  1. page.php
  2. singular.php
  3. index.php

In summary:

  • Use single.php to target individual blog posts (or posts of specific post types).
  • Use singular.php as a more general fallback for displaying any singular piece of content, including posts, pages, or custom post types.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment