Skip to content
  • Quick Ref
  • Contact
  • About
wpcanyon.com

wpcanyon.com

Tag: Loop

Solution previous_posts_link and next_posts_link Not Working

Posted on August 20, 2025August 20, 2025 By Admin No Comments on Solution previous_posts_link and next_posts_link Not Working

Solution previous_posts_link and next_posts_link Not Working

If you are using WordPress and find that the previous_posts_link() and next_posts_link() functions are not working as expected, this guide will help you quickly fix the issue. These functions are essential for navigating between paginated blog posts or archive pages, and when they fail, it can disrupt user experience and site navigation.

Quick Fix

  1. Ensure you are using query_posts() or the main query properly without overwriting it incorrectly.
  2. Use paginate_links() or the correct loop structure if you have a custom query.
  3. Verify that your theme’s index.php, archive.php, or relevant template files include the pagination functions inside the main loop.
  4. Check your permalink settings and flush rewrite rules by saving permalinks again in the WordPress admin.
  5. Make sure you are not calling these functions outside the WordPress Loop or without a proper query context.

Why This Happens

The previous_posts_link() and next_posts_link() functions rely on the global WordPress query object ($wp_query) to determine pagination. If you modify the query incorrectly, such as by using query_posts() improperly or creating a new WP_Query without setting up pagination parameters, these functions won’t work because they don’t have the correct context.

Additionally, calling these functions outside the loop or on pages without pagination will cause them to fail or not display links. Permalink issues or rewrite rules can also interfere with pagination URLs.

Step-by-Step

  1. Check your main query usage: Avoid using query_posts() as it overrides the main query and can break pagination. Instead, use pre_get_posts filter or WP_Query properly.
  2. Use the main loop for pagination: Make sure your pagination functions are inside the main loop or use the global $wp_query.
  3. Flush rewrite rules: Go to Settings > Permalinks in your WordPress admin and click “Save Changes” to refresh rewrite rules.
  4. Implement correct pagination for custom queries: If you use a custom WP_Query, pass the current page parameter and use paginate_links() or custom pagination code.
  5. Test your pagination: Navigate through your blog or archive pages to verify that the previous and next links appear and work correctly.

Code Snippets

Correct Usage in Main Loop (index.php or archive.php)

<?php if ( have_posts() ) : ?>
  <?php while ( have_posts() ) : the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <div><?php the_excerpt(); ?></div>
  <?php endwhile; ?>

  <div class="pagination">
    <?php previous_posts_link('Newer Posts'); ?>
    <?php next_posts_link('Older Posts'); ?>
  </div>

<?php else : ?>
  <p>No posts found.</p>
<?php endif; ?>

Proper Custom Query Pagination

<?php
$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();
    ?>
    <h2><?php the_title(); ?></h2>
    <div><?php the_excerpt(); ?></div>
    <?php
  endwhile;

  $big = 999999999; // need an unlikely integer

  echo paginate_links( array(
    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format' => '?paged=%#%',
    'current' => max( 1, get_query_var('paged') ),
    'total' => $custom_query->max_num_pages
  ) );

  wp_reset_postdata();
else :
  ?>
  <p>No posts found.</p>
  <?php
endif;
?>

Common Pitfalls

  • Using query_posts() without resetting the query causes pagination to break.
  • Calling previous_posts_link() and next_posts_link() outside the loop or outside the main query context.
  • Not passing the paged parameter in custom queries.
  • Permalink structure issues that require flushing rewrite rules.
  • Using custom queries without resetting post data (wp_reset_postdata()).

Test & Verify

  1. Visit your blog or archive page with multiple pages of posts.
  2. Check if the “Older Posts” and “Newer Posts” links appear at the bottom.
  3. Click the links to navigate between pages and verify the URL changes correctly.
  4. If using a custom query, ensure the pagination links reflect the correct page numbers.
  5. Use browser developer tools to check for any JavaScript or PHP errors.

Wrap-up

Fixing previous_posts_link() and next_posts_link() not working usually involves ensuring proper use of the WordPress query system and pagination parameters. Avoid overriding the main query incorrectly, always pass the paged parameter for custom queries, and flush rewrite rules after permalink changes. Following the steps and code examples above will restore pagination functionality on your WordPress site.

Works on: Apache, Nginx, LiteSpeed servers; compatible with cPanel and Plesk hosting environments; WordPress versions 4…

Queries & Pagination

Shortcode: list posts by tag with excerpt

Posted on August 19, 2025 By Admin No Comments on Shortcode: list posts by tag with excerpt

Shortcode: List Posts by Tag with Excerpt in WordPress

If you want to display a list of posts filtered by a specific tag along with their excerpts anywhere on your WordPress site, using a shortcode is a practical and flexible solution. This tutorial shows you how to create a custom shortcode that lists posts by tag with excerpts, so you can easily embed it in posts, pages, or widgets.

When to Use This Shortcode

  • You want to highlight related content by tag on a page or post.
  • You need a dynamic list of posts filtered by tags without manually updating links.
  • You want to show post excerpts alongside titles for better context.
  • You prefer a shortcode solution that can be reused and customized easily.

Quick Fix: Create a Shortcode to List Posts by Tag with Excerpt

  1. Add the provided PHP code to your theme’s functions.php file or create a mini-plugin.
  2. Use the shortcode [posts_by_tag tag="your-tag-slug" posts="5"] in your content.
  3. Adjust parameters like tag slug and number of posts as needed.
  4. Test the shortcode on a page or post to verify output.

Why This Happens

WordPress does not have a built-in shortcode to list posts filtered by tag with excerpts. The default shortcodes like [recent_posts] or widgets do not provide flexible tag filtering combined with excerpts. Creating a custom shortcode leverages WordPress’s WP_Query class to fetch posts by tag and outputs them in a clean, reusable format.

Step-by-Step: Add the Shortcode Code

Below is the complete PHP code for the shortcode. It accepts two attributes:

  • tag: The slug of the tag to filter posts by (required).
  • posts: Number of posts to display (optional, default is 5).
<?php
// Shortcode to list posts by tag with excerpt
function shortcode_list_posts_by_tag_with_excerpt($atts) {
    // Set default attributes and merge with user input
    $atts = shortcode_atts(
        array(
            'tag' => '',        // Tag slug to filter by
            'posts' => 5       // Number of posts to show
        ), 
        $atts, 
        'posts_by_tag'
    );

    // Sanitize inputs
    $tag_slug = sanitize_text_field($atts['tag']);
    $posts_per_page = intval($atts['posts']);
    if ($posts_per_page <= 0) {
        $posts_per_page = 5;
    }

    if (empty($tag_slug)) {
        return '<p>Please provide a tag slug in the shortcode attribute.</p>';
    }

    // Query posts by tag
    $query_args = array(
        'tag' => $tag_slug,
        'posts_per_page' => $posts_per_page,
        'post_status' => 'publish',
        'ignore_sticky_posts' => true,
    );

    $query = new WP_Query($query_args);

    if (!$query->have_posts()) {
        return '<p>No posts found for tag: ' . esc_html($tag_slug) . '</p>';
    }

    // Start output buffering
    ob_start();

    echo '<ul class="posts-by-tag-list">';

    while ($query->have_posts()) {
        $query->the_post();
        echo '<li>';
        echo '<a href="' . esc_url(get_permalink()) . '">' . esc_html(get_the_title()) . '</a>';
        echo '<p class="post-excerpt">' . esc_html(get_the_excerpt()) . '</p>';
        echo '</li>';
    }

    echo '</ul>';

    wp_reset_postdata();

    return ob_get_clean();
}
add_shortcode('posts_by_tag', 'shortcode_list_posts_by_tag_with_excerpt');
?>

How to Add This Code

  1. Via functions.php: Open your active theme’s functions.php file and paste the above code at the end.
  2. Via Mini-Plugin: Create a new file named posts-by-tag-shortcode.php in wp-content/plugins/ with the following header and the code above:
<?php
/*
Plugin Name: Posts By Tag Shortcode
Description: Adds a shortcode to list posts by tag with excerpts.
Version: 1.0
Author: Your Name
*/
 
// Paste the shortcode function code here
?>

Then activate the plugin from the WordPress admin.

Testing the Shortcode

  1. Create or edit a post/page where you want to display the list.
  2. Insert the shortcode with your desired tag slug and number of posts, for example:
[posts_by_tag tag="news" posts="3"]

This will display the 3 most recent posts tagged with news, showing their titles linked to the posts and excerpts below.

Variations and Customizations

  • Change number of posts: Adjust the posts attribute, e.g. posts="10".
  • Style output: Add CSS targeting .posts-by-tag-list and .post-excerpt classes.
  • Show full content: Replace get_the_excerpt() with get_the_content() in the code.
  • Order posts: Modify $query_args to include 'orderby' => 'date' or other parameters.
  • Multiple tags: Extend the shortcode to accept comma-separated tags by adjusting the query.

Works On

Environment Notes
Apache, Nginx, LiteSpeed Compatible with all standard web servers running WordPress.
cPanel, Plesk Works on hosting control panels with standard WordPress installations.
PHP
…
Developer Snippets

WP_Query: exclude a category (and paginated archives)

Posted on August 19, 2025 By Admin No Comments on WP_Query: exclude a category (and paginated archives)

WP_Query: Exclude a Category (and Paginated Archives)

If you want to display posts on your WordPress site but exclude one or more categories — including on paginated archive pages — the WP_Query class is your go-to solution. This tutorial shows you how to exclude categories properly, ensuring pagination works seamlessly without showing posts from unwanted categories.

When to Use This

  • You want to customize your blog or archive pages to hide posts from specific categories.
  • You need to exclude categories on paginated archive pages without breaking pagination.
  • You want to create custom loops or queries that omit certain categories.

Quick Fix: Exclude Categories in WP_Query

  1. Use the category__not_in parameter in WP_Query to exclude categories by ID.
  2. Ensure pagination parameters are correctly passed to maintain paginated archives.
  3. Add the code snippet to your theme’s functions.php or a custom plugin.
  4. Test on archive and paginated pages to confirm excluded categories don’t appear.

Why This Happens

By default, WordPress queries include posts from all categories unless filtered. Using category__not_in tells WordPress to exclude posts assigned to specific category IDs. However, if pagination is not handled correctly, excluding categories can cause pagination to break or display unexpected results because the total post count changes.

Properly passing the current page number and using WP_Query with exclusion parameters ensures WordPress calculates pagination based on the filtered posts, maintaining correct page counts and navigation.

Step-by-Step: Exclude a Category with Pagination Support

  1. Identify the category ID(s) you want to exclude. You can find this in the WordPress admin under Posts → Categories. Hover over a category name and note the ID from the URL (e.g., tag_ID=5).
  2. Create a custom query using WP_Query with the category__not_in parameter and pagination support.
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 10,
    'paged'          => $paged,
    'category__not_in' => array(5), // Replace 5 with your category ID(s)
);

$custom_query = new WP_Query( $args );

if ( $custom_query->have_posts() ) :
    while ( $custom_query->have_posts() ) : $custom_query->the_post();
        the_title('<h2>', '</h2>');
        the_excerpt();
    endwhile;

    // Pagination
    echo paginate_links( array(
        'total'   => $custom_query->max_num_pages,
        'current' => $paged,
    ) );

    wp_reset_postdata();
else :
    echo '<p>No posts found.</p>';
endif;
?>

Add via functions.php or Mini-Plugin

You can add the above code directly in a custom page template or inside a shortcode function for easier reuse. Here is an example shortcode you can add to your theme’s functions.php or a small plugin file:

<?php
function exclude_category_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'exclude' => '', // comma-separated category IDs
        'posts_per_page' => 5,
    ), $atts, 'exclude_category' );

    $exclude_ids = array_map( 'intval', explode( ',', $atts['exclude'] ) );
    $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => intval( $atts['posts_per_page'] ),
        'paged'          => $paged,
        'category__not_in' => $exclude_ids,
    );

    $query = new WP_Query( $args );

    ob_start();

    if ( $query->have_posts() ) :
        while ( $query->have_posts() ) : $query->the_post();
            echo '<h2>' . get_the_title() . '</h2>';
            echo get_the_excerpt();
        endwhile;

        echo paginate_links( array(
            'total'   => $query->max_num_pages,
            'current' => $paged,
        ) );

        wp_reset_postdata();
    else :
        echo '<p>No posts found.</p>';
    endif;

    return ob_get_clean();
}
add_shortcode( 'exclude_category', 'exclude_category_shortcode' );
?>

Use the shortcode in posts or pages like this:

[exclude_category exclude="5,7" posts_per_page="10"]

Testing

  1. Place the code in your theme or use the shortcode on a page.
  2. Visit the page and verify posts from the excluded categories do not appear.
  3. Navigate to paginated pages (e.g., /page/2/) and confirm pagination works and excluded categories remain hidden.
  4. Check for any 404 errors or empty pages and adjust posts_per_page or category IDs if needed.

Variations

  • Exclude multiple categories: Pass multiple IDs in the array, e.g., 'category__not_in' => array(5, 7, 9).
  • Exclude by slug: Use tax_query instead of category__not_in for more complex queries.
  • Exclude categories on main blog page: Use the pre_get_posts action hook to modify the main query.

Works on

Environment Notes
Apache Fully compatible; standard WordPress setup.
Nginx Works as expected; ensure permalinks are configured correctly.
LiteSpeed Compatible; no special configuration needed.
…
Developer Snippets

Showing Random Posts In WordPress

Posted on August 19, 2025 By Admin No Comments on Showing Random Posts In WordPress

Showing Random Posts in WordPress

Displaying random posts in WordPress is a popular way to increase user engagement by showcasing diverse content each time a visitor lands on your site. Whether you want to highlight different blog posts, products, or portfolio items, showing random posts keeps your site dynamic and encourages visitors to explore more.

Quick Fix: Show Random Posts in WordPress

  1. Use the WP_Query class with 'orderby' => 'rand' to fetch random posts.
  2. Add the code snippet to your theme’s functions.php or create a small plugin.
  3. Call the function in your template files or use a shortcode to display random posts anywhere.

Why This Happens

WordPress does not provide a built-in widget or block to show random posts by default. You need to customize the query to order posts randomly. Using 'orderby' => 'rand' in WP_Query instructs WordPress to shuffle the posts before returning them. This approach is simple and effective but requires adding custom PHP code or using a plugin.

When to Use Showing Random Posts

  • Increase page views: Encourage visitors to browse more content.
  • Highlight older posts: Give visibility to posts that might otherwise be overlooked.
  • Enhance user experience: Make your site feel fresh and dynamic on each visit.
  • Promote diverse content: Showcase different categories or post types randomly.

Updated Code for Modern WordPress

Here is a clean, modern, and reusable function to fetch and display random posts. It uses WP_Query with proper escaping and supports customization of post type and number of posts.

function show_random_posts( $args = array() ) {
    $defaults = array(
        'post_type'      => 'post',
        'posts_per_page' => 5,
        'orderby'        => 'rand',
        'post_status'    => 'publish',
    );

    $query_args = wp_parse_args( $args, $defaults );

    $random_query = new WP_Query( $query_args );

    if ( $random_query->have_posts() ) {
        echo '<ul class="random-posts-list">';
        while ( $random_query->have_posts() ) {
            $random_query->the_post();
            echo '<li><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></li>';
        }
        echo '</ul>';
        wp_reset_postdata();
    } else {
        echo '<p>No posts found.</p>';
    }
}

How to Add This via functions.php or a Small Plugin

Option 1: Add to functions.php

  1. Open your active theme folder.
  2. Locate and edit the functions.php file.
  3. Paste the show_random_posts() function code at the end.
  4. Call show_random_posts(); in any template file where you want to display random posts.

Option 2: Create a Small Plugin

  1. Create a new folder named random-posts-display in wp-content/plugins.
  2. Create a file random-posts-display.php inside that folder.
  3. Paste the following code:
<?php
/**
 * Plugin Name: Random Posts Display
 * Description: Display random posts anywhere using a shortcode.
 * Version: 1.0
 * Author: Your Name
 */

function rpd_show_random_posts( $atts ) {
    $atts = shortcode_atts( array(
        'post_type'      => 'post',
        'posts_per_page' => 5,
    ), $atts, 'random_posts' );

    $query_args = array(
        'post_type'      => sanitize_text_field( $atts['post_type'] ),
        'posts_per_page' => intval( $atts['posts_per_page'] ),
        'orderby'        => 'rand',
        'post_status'    => 'publish',
    );

    $random_query = new WP_Query( $query_args );

    if ( $random_query->have_posts() ) {
        $output = '<ul class="random-posts-list">';
        while ( $random_query->have_posts() ) {
            $random_query->the_post();
            $output .= '<li><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></li>';
        }
        $output .= '</ul>';
        wp_reset_postdata();
    } else {
        $output = '<p>No posts found.</p>';
    }

    return $output;
}
add_shortcode( 'random_posts', 'rpd_show_random_posts' );
  1. Activate the plugin via the WordPress admin dashboard.
  2. Use the shortcode [random_posts] in posts, pages, or widgets to display random posts.

Step-by-Step Test

  1. Add the function or plugin code as described above.
  2. Insert <?php show_random_posts(); ?> in a theme template file (e.g., sidebar.php or footer.php).
  3. Or add the shortcode [random_posts] in the WordPress editor.
  4. Visit your site’s front end and refresh the page multiple times.
  5. Verify that different posts appear randomly each time.

Block Themes & Gutenberg Notes

For block themes or full site editing (FSE), you cannot directly insert PHP code in blocks. Instead, use the shortcode method via a Shortcode block or create a custom block plugin that wraps this functionality.

  • Insert a Shortcode block and add [random_posts].
  • For advanced users, create a dynamic block that calls show_random_posts() on render.
  • Remember that caching plugins or server-side caching might prevent the randomization from updating on
…
WordPress Snippets

Recent Posts

  • Top WordPress Themes for Blogs in 2025
  • WordPress Admin Panel Trick: Adding ID Field to the Posts Listing
  • Solution previous_posts_link and next_posts_link Not Working
  • Show Top Commentators in WordPress Without a Plugin
  • How to Style Admin Comments in WordPress

Recent Comments

    Archives

    • August 2025

    Categories

    • Admin & Blocks
    • Admin & UI
    • Automation
    • Automation & Plugins
    • Comments
    • Comparisons
    • Database & Revisions
    • Developer Snippets
    • Fixes & Errors
    • Media & Thumbnails
    • Queries & Pagination
    • Security
    • Speed & Security
    • Tips & Tricks
    • WooCommerce How‑tos
    • WordPress Snippets
    • WordPress Themes
    • Terms & Conditions
    • Affiliate Disclosure

    Copyright © 2025 wpcanyon.com.

    Powered by PressBook WordPress theme

    Also by the maker of MySurveyReviews.com