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

wpcanyon.com

Tag: WordPress

Fix “Sorry, you are not allowed to access this page”

Posted on August 19, 2025 By Admin No Comments on Fix “Sorry, you are not allowed to access this page”

Fix “Sorry, you are not allowed to access this page” in WordPress

If you see the message “Sorry, you are not allowed to access this page” when trying to access your WordPress admin dashboard or certain pages, it usually means your user permissions or site configuration are misconfigured. This error can block you from managing your site, but the fix is often straightforward.

Quick fix: Reset your user roles and capabilities or fix your site’s .htaccess or Nginx config to restore proper access.

Quick Fix

  1. Access your WordPress database via phpMyAdmin or a database client.
  2. Run this SQL query to reset your admin user capabilities (replace 1 with your user ID if different):
DELETE FROM wp_usermeta WHERE user_id = 1 AND meta_key = 'wp_capabilities';
INSERT INTO wp_usermeta (user_id, meta_key, meta_value) VALUES (1, 'wp_capabilities', 'a:1:{s:13:"administrator";b:1;}');
  1. Check your .htaccess (Apache) or Nginx config for incorrect rules blocking access.
  2. Clear your browser cache and cookies, then log in again.

Why This Happens

  • Corrupted user roles or capabilities: Plugins or manual changes can accidentally remove or alter administrator capabilities, causing WordPress to block access.
  • Incorrect file permissions or ownership: Server permissions that restrict access to key WordPress files can trigger this error.
  • Misconfigured .htaccess or Nginx rules: Security rules or redirects may unintentionally block admin pages.
  • Plugin or theme conflicts: Faulty or incompatible plugins/themes can interfere with user permissions.
  • Database issues: Corrupted or missing database entries related to user roles.

Step-by-step Fix

1. Reset Administrator Capabilities via Database

Use phpMyAdmin or your preferred database tool to run these commands. Replace wp_ with your database prefix if different, and 1 with your admin user ID if needed.

DELETE FROM wp_usermeta WHERE user_id = 1 AND meta_key = 'wp_capabilities';

INSERT INTO wp_usermeta (user_id, meta_key, meta_value) VALUES (1, 'wp_capabilities', 'a:1:{s:13:"administrator";b:1;}');

This removes any corrupted capabilities and restores administrator rights.

2. Check and Fix File Permissions

Connect to your server via SSH or FTP and run these commands to set correct permissions:

find /path/to/wordpress/ -type d -exec chmod 755 {} ;
find /path/to/wordpress/ -type f -exec chmod 644 {} ;

Replace /path/to/wordpress/ with your actual WordPress root directory.

3. Verify .htaccess (Apache) or Nginx Configuration

For Apache: Check your .htaccess file in the WordPress root. It should contain the standard WordPress rules:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

If you have custom rules blocking access, comment them out or remove them temporarily.

For Nginx: Check your site configuration file, usually located in /etc/nginx/sites-available/. Ensure your location blocks allow access to /wp-admin and /wp-login.php. A minimal working example:

location /wp-admin/ {
    try_files $uri $uri/ /index.php?$args;
}

location = /wp-login.php {
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # adjust PHP version/socket
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

Reload Nginx after changes:

sudo nginx -t
sudo systemctl reload nginx

4. Disable All Plugins Temporarily

If the problem persists, disable plugins by renaming the plugins folder via FTP or SSH:

mv /path/to/wordpress/wp-content/plugins /path/to/wordpress/wp-content/plugins-disabled

Try accessing the admin again. If successful, rename the folder back and reactivate plugins one by one to find the culprit.

5. Switch to Default Theme

Rename your active theme folder to force WordPress to use a default theme like Twenty Twenty-One:

mv /path/to/wordpress/wp-content/themes/your-active-theme /path/to/wordpress/wp-content/themes/your-active-theme-disabled

Check if access is restored.

Works on

Environment Notes
Apache Fixes .htaccess and permissions issues
Nginx Fixes server config for admin access
cPanel Access phpMyAdmin, file manager, and terminal for fixes
Plesk Use database manager and file manager for troubleshooting
LiteSpeed Similar to Apache, check .htaccess and permissions

FAQ

Q1: I can’t access phpMyAdmin. How else can I reset user capabilities?

If you have SSH access, you can use WP-CLI commands:

wp user set-role 1 administrator

This sets user ID 1 to administrator.

Q2: Could a plugin cause this error?

Yes. Plugins that modify user roles or security plugins can cause permission issues. Disable plugins temporarily to test.

Q3: What if I still can’t access wp-admin

…
Fixes & Errors

Fix “Briefly unavailable for scheduled maintenance” in WordPress

Posted on August 19, 2025 By Admin No Comments on Fix “Briefly unavailable for scheduled maintenance” in WordPress

Fix “Briefly unavailable for scheduled maintenance” in WordPress

If you’ve ever updated a WordPress plugin, theme, or core and seen the message “Briefly unavailable for scheduled maintenance. Check back in a minute.” stuck on your site, you’re not alone. This message appears when WordPress is in maintenance mode during updates, but sometimes it doesn’t disappear automatically. The quick fix is to manually delete the .maintenance file from your WordPress root directory.

Quick Fix

  1. Access your website files via FTP, SFTP, or your hosting file manager.
  2. Locate the .maintenance file in the root folder of your WordPress installation.
  3. Delete the .maintenance file.
  4. Reload your website to confirm it’s back online.

Why This Happens

When WordPress performs updates, it creates a temporary .maintenance file in the root directory to put the site into maintenance mode. This prevents visitors from seeing broken or incomplete pages during the update process.

Normally, WordPress deletes this file automatically once the update finishes. However, if the update is interrupted — due to server timeout, connection issues, or plugin conflicts — the .maintenance file remains, causing the site to stay stuck in maintenance mode.

Step-by-step: Fixing the Issue

For Nginx or Apache Servers

  1. Connect to your server using an FTP client like FileZilla or via SSH.
  2. Navigate to your WordPress root directory (where wp-config.php is located).
  3. Look for the .maintenance file. It may be hidden, so ensure your FTP client shows hidden files.
  4. Delete the .maintenance file.
  5. Clear your browser cache and reload your website.
# Example SSH commands:
cd /path/to/wordpress
rm .maintenance

For cPanel or Plesk Users

  1. Log in to your hosting control panel (cPanel or Plesk).
  2. Open the File Manager.
  3. Navigate to your WordPress root directory (usually public_html or a subfolder).
  4. Enable “Show Hidden Files” if not already enabled.
  5. Find and delete the .maintenance file.
  6. Reload your website to verify the fix.

Works on

  • Web servers: Nginx, Apache, LiteSpeed
  • Hosting control panels: cPanel, Plesk, DirectAdmin
  • File access methods: FTP, SFTP, SSH, Hosting File Managers
  • WordPress versions: All versions that use the maintenance mode file during updates

FAQ

Q: What if I don’t see the .maintenance file?
A: Make sure your FTP client or file manager shows hidden files. The .maintenance file is hidden by default because of the leading dot.
Q: Can I just wait for the maintenance mode to end?
A: Usually yes, but if the update process was interrupted, the site will stay stuck. Manual removal of the .maintenance file is needed.
Q: Will deleting the .maintenance file cause any data loss?
A: No, deleting this file only ends maintenance mode. It does not affect your database or content.
Q: How can I prevent this from happening again?
A: Ensure your server has enough resources and stable connections during updates. Avoid interrupting updates manually and keep plugins/themes compatible and updated.
Q: Is there a plugin to fix this automatically?
A: Some plugins can detect and remove the maintenance file, but manual removal is the most reliable and fastest method.
…
Fixes & Errors

Adding Classes to body_class() in WordPress

Posted on August 19, 2025 By Admin No Comments on Adding Classes to body_class() in WordPress

Adding Classes to body_class() in WordPress

When building or customizing WordPress themes, you often need to add custom CSS classes to the <body> tag for styling or JavaScript targeting. WordPress provides the body_class() function to output classes dynamically, but sometimes you want to add your own classes programmatically. This tutorial explains how to add classes to body_class() in WordPress the right way, with updated code for modern WordPress, including block themes and Gutenberg considerations.

Quick Fix: How to Add Classes to body_class()

  1. Open your theme’s functions.php file or create a small plugin.
  2. Add a filter to body_class that appends your custom classes.
  3. Test by viewing your site’s source code and verifying the <body> tag classes.

Why This Happens

The body_class() function outputs an array of CSS classes for the <body> tag, reflecting the current page context (e.g., home, single post, category). By default, WordPress controls these classes, but developers often need to add custom classes for additional styling or scripting purposes. Directly editing theme templates to hardcode classes is not recommended because it breaks flexibility and maintainability. Instead, WordPress provides a filter hook body_class to safely modify or add classes.

When to Use Custom Classes in body_class()

  • Adding page-specific or user-specific CSS hooks.
  • Targeting custom post types or taxonomies with CSS or JS.
  • Adding classes based on user roles or login status.
  • Conditionally styling parts of your theme without modifying templates.

Updated Code for Modern WordPress

Since WordPress 5.0+ and the rise of block themes and Gutenberg, the method to add classes remains the same but you should ensure your code is compatible with block-based templates and full site editing.

Here is the recommended approach using the body_class filter:

function my_custom_body_classes( $classes ) {
    // Add a custom class
    $classes[] = 'my-custom-class';

    // Conditionally add a class on the homepage
    if ( is_front_page() ) {
        $classes[] = 'front-page-class';
    }

    // Add class if user is logged in
    if ( is_user_logged_in() ) {
        $classes[] = 'logged-in-user';
    }

    return $classes;
}
add_filter( 'body_class', 'my_custom_body_classes' );

How to Add Custom Classes via functions.php or a Small Plugin

  1. Via functions.php:

    Open your active theme’s functions.php file and paste the code snippet above at the end of the file.

  2. Via a small plugin:

    Create a new PHP file in wp-content/plugins/ named custom-body-classes.php with the following content:

    <?php
        /*
        Plugin Name: Custom Body Classes
        Description: Adds custom classes to the body tag.
        Version: 1.0
        Author: Your Name
        */
    
        function my_custom_body_classes( $classes ) {
            $classes[] = 'my-custom-class';
            if ( is_front_page() ) {
                $classes[] = 'front-page-class';
            }
            if ( is_user_logged_in() ) {
                $classes[] = 'logged-in-user';
            }
            return $classes;
        }
        add_filter( 'body_class', 'my_custom_body_classes' );
        

    Then activate this plugin from the WordPress admin.

Step-by-Step Test

  1. Add the code snippet to your functions.php or activate the plugin.
  2. Clear any caches if you use caching plugins or server caching.
  3. Visit your homepage and view the page source (right-click > View Page Source).
  4. Locate the <body> tag and verify your custom classes appear, e.g., my-custom-class and front-page-class.
  5. Log in to your WordPress admin and refresh the page to confirm logged-in-user class appears.
  6. Test on other pages to verify classes change according to conditions.

Block Themes & Gutenberg Notes

Block themes and the Full Site Editing (FSE) experience introduced in WordPress 5.9+ do not change how body_class() works. The body_class filter remains the standard way to add classes. However, some block themes may use different templates or wrappers, so ensure your theme calls body_class() in the <body> tag.

For block themes, you can also add classes via the theme.json file or custom block styles, but for global body classes, the filter method is still best.

Common Pitfalls

  • Not returning the modified classes array: Always return the modified $classes array in your filter function.
  • Adding classes as a string: The filter expects an array of classes, so add classes by appending to the array, not as a string.
  • Forgetting to hook the filter: Make sure to add add_filter( 'body_class', 'your_function' );.
  • Cache issues: Changes might not appear immediately if caching plugins or server caches are active.
  • Theme compatibility: Some themes may override body_class() or not call it properly; verify your theme outputs it in the <body> tag.

Works On

Server/Environment Compatibility
Apache Fully compatible
Nginx Fully compatible
LiteSpeed Fully compatible
…
WordPress Snippets

Adding ID Field To The Media Library Listing In WordPress Admin

Posted on August 19, 2025 By Admin No Comments on Adding ID Field To The Media Library Listing In WordPress Admin

Adding ID Field To The Media Library Listing In WordPress Admin

If you manage a WordPress site with many media files, you might find it useful to see the attachment ID directly in the Media Library list. By default, WordPress does not show the media ID column, which can make referencing or debugging media items harder. This tutorial shows you how to media library show ID column WordPress with a quick code snippet you can add to your theme’s functions.php file or a small custom plugin.

When to Use This

  • You need to quickly find the attachment ID for shortcodes, custom queries, or debugging.
  • You want to improve your workflow by seeing media IDs without opening each file.
  • You are developing or managing a site with many media files and want better admin visibility.

Updated Code for Modern WordPress

WordPress has evolved, and the admin list tables now support hooks to add custom columns easily. The following code uses the manage_upload_columns and manage_media_custom_column filters to add an ID column to the Media Library list view.

Quick Fix: Add ID Column to Media Library

  1. Open your active theme’s functions.php file or create a small plugin.
  2. Copy and paste the code below to add the ID column.
  3. Save and refresh the Media Library (list view) in the WordPress admin.
<?php
// Add ID column to Media Library list view
add_filter('manage_upload_columns', 'add_media_id_column');
function add_media_id_column($columns) {
    $new_columns = array();
    foreach ($columns as $key => $value) {
        if ($key === 'title') { // Insert ID column before Title
            $new_columns['media_id'] = 'ID';
        }
        $new_columns[$key] = $value;
    }
    return $new_columns;
}

add_action('manage_media_custom_column', 'show_media_id_column', 10, 2);
function show_media_id_column($column_name, $post_id) {
    if ($column_name === 'media_id') {
        echo $post_id;
    }
}
?>

Step-by-Step: Add via functions.php or a Small Plugin

  1. Via functions.php:
    1. Access your site files via FTP or hosting file manager.
    2. Navigate to wp-content/themes/your-active-theme/.
    3. Edit the functions.php file.
    4. Paste the code snippet above at the end of the file.
    5. Save changes and upload if needed.
    6. Go to WordPress admin > Media > Library and switch to List View.
    7. You should see a new “ID” column showing the media item IDs.
  2. Via a small plugin:
    1. Create a new file named media-library-id-column.php.
    2. Paste the following code inside:
    3. <?php
      /*
      Plugin Name: Media Library ID Column
      Description: Adds an ID column to the WordPress Media Library list view.
      Version: 1.0
      Author: Your Name
      */
      
      add_filter('manage_upload_columns', 'add_media_id_column');
      function add_media_id_column($columns) {
          $new_columns = array();
          foreach ($columns as $key => $value) {
              if ($key === 'title') {
                  $new_columns['media_id'] = 'ID';
              }
              $new_columns[$key] = $value;
          }
          return $new_columns;
      }
      
      add_action('manage_media_custom_column', 'show_media_id_column', 10, 2);
      function show_media_id_column($column_name, $post_id) {
          if ($column_name === 'media_id') {
              echo $post_id;
          }
      }
      ?>
      
    4. Upload the file to wp-content/plugins/.
    5. Activate the plugin via WordPress admin > Plugins.
    6. Check the Media Library list view for the new ID column.

Step-by-Step Test

  1. Log in to WordPress admin.
  2. Navigate to Media > Library.
  3. Make sure the view mode is set to List View (not Grid View).
  4. Look for the new ID column next to the Title column.
  5. Verify the numbers correspond to the media item IDs by clicking “Edit” on a media item and checking the URL (e.g., post.php?post=123&action=edit).

Block Themes & Gutenberg Notes

Block themes and the Gutenberg editor do not affect the Media Library list table in the admin area. This code works independently of the front-end theme or editor. However, if you use a full site editing (FSE) block theme, the Media Library admin screen remains the same and will display the ID column as expected.

Common Pitfalls

  • No ID column visible: Make sure you are in List View, not Grid View. The column only appears in List View.
  • Code added but no effect: Clear any caching plugins or browser cache. Also, verify the code is in the active theme’s functions.php or the plugin is activated.
  • Syntax errors: Copy-paste carefully and ensure PHP tags are correct. A syntax error can break your site.
  • Child theme usage: If you use a child theme, add the code to the child theme’s functions.php to avoid losing changes on updates.

Why This Happens

By default, WordPress does not include the attachment ID as a visible column in the Media Library list table. The list table is customizable via hooks, but the ID column is not enabled out of the box. Adding the ID column requires hooking into WordPress filters that control which columns are displayed and what content they show.

Works On

Environment Notes
Apache, Nginx, LiteSpeed Works on all common web servers as this is a WordPress PHP hook change.
…
WordPress Snippets

Adding Classes To previous_posts_link() And next_posts_link() In WordPress

Posted on August 19, 2025 By Admin No Comments on Adding Classes To previous_posts_link() And next_posts_link() In WordPress

Adding Classes To previous_posts_link() And next_posts_link() In WordPress

By default, WordPress’s previous_posts_link() and next_posts_link() functions generate simple anchor tags without any CSS classes. This limits your ability to style these pagination links easily. The quick fix is to add custom classes to these links, enabling better control over their appearance and behavior.

Quick Fix

  1. Use the updated versions of previous_posts_link() and next_posts_link() that accept an additional argument for classes.
  2. Add a filter in your functions.php or a small plugin to inject classes into the generated markup.
  3. Test the changes on your archive or blog pages to confirm the classes are applied.

Why This Happens

WordPress’s core functions previous_posts_link() and next_posts_link() were originally designed to output simple pagination links without class attributes. While modern WordPress versions allow some customization, these functions do not natively accept a class parameter. As a result, developers must use filters or custom wrappers to add classes for styling purposes.

When To Use

  • You want to style the “Previous” and “Next” pagination links differently from other links.
  • You are building a custom theme or child theme and need consistent markup.
  • You want to add JavaScript hooks or accessibility improvements via classes.

Updated Code For Modern WordPress

Since WordPress 5.9, the paginate_links() function and the_posts_pagination() support class arguments more directly, but previous_posts_link() and next_posts_link() do not. To add classes, you can use the get_previous_posts_link and get_next_posts_link filters to modify the output.

How To Add Classes via functions.php or a Small Plugin

Add the following code to your theme’s functions.php file or a custom plugin to add classes my-prev-class and my-next-class to the respective links:

/ Add custom class to previous_posts_link
function add_class_to_previous_posts_link( $link ) {
    if ( strpos( $link, 'class=' ) === false ) {
        $link = str_replace( '<a ', '<a class="my-prev-class" ', $link );
    } else {
        $link = str_replace( 'class="', 'class="my-prev-class ', $link );
    }
    return $link;
}
add_filter( 'previous_posts_link', 'add_class_to_previous_posts_link' );

/ Add custom class to next_posts_link
function add_class_to_next_posts_link( $link ) {
    if ( strpos( $link, 'class=' ) === false ) {
        $link = str_replace( '<a ', '<a class="my-next-class" ', $link );
    } else {
        $link = str_replace( 'class="', 'class="my-next-class ', $link );
    }
    return $link;
}
add_filter( 'next_posts_link', 'add_class_to_next_posts_link' );

Step-by-step Test

  1. Open your theme’s functions.php file or create a new plugin file.
  2. Copy and paste the code above into the file.
  3. Save and upload the file to your WordPress installation.
  4. Navigate to a paginated archive page (e.g., blog posts page).
  5. Inspect the “Previous” and “Next” pagination links in your browser’s developer tools.
  6. Confirm the links have the classes my-prev-class and my-next-class respectively.
  7. Apply CSS styles targeting these classes to customize the appearance.

Block Themes & Gutenberg Notes

With the rise of block themes and Gutenberg, pagination is often handled by blocks like the “Query Pagination” block. These blocks provide UI options to add classes directly in the editor. However, if you are using classic PHP templates or custom blocks that rely on previous_posts_link() and next_posts_link(), the above method remains valid.

For block themes, consider using the block editor’s built-in className controls or creating block variations with custom classes. For PHP-based themes, the filter method is the most straightforward approach.

Common Pitfalls

  • Classes not appearing: Ensure you are editing the correct functions.php file and that no other plugin or theme overrides the pagination output.
  • Multiple classes conflict: If the link already has classes, the code appends your class rather than replacing it to avoid conflicts.
  • Cache issues: Clear any caching plugins or server cache after making changes.
  • Incorrect HTML escaping: Use the filters exactly as shown to avoid breaking HTML output.

FAQ

Question Answer
Can I add multiple classes to the links? Yes. Modify the class string in the str_replace calls to include multiple classes separated by spaces, e.g., class="my-prev-class another-class".
Will this work with custom pagination plugins? Only if those plugins use previous_posts_link() and next_posts_link(). Otherwise, you need to check the plugin’s documentation for adding classes.
Can I add classes directly in the template files? No. The core functions do not accept a class parameter. You must use filters or custom markup to add classes.
Does this method affect SEO or accessibility? No. Adding classes does not affect SEO or accessibility negatively. You can even improve accessibility by adding ARIA attributes alongside classes.
Is this compatible with all WordPress versions? This method works on WordPress 4.7 and later, as the filters previous_posts_link and next_posts_link have been available since then.

Works on

  • Apache, Nginx
…
WordPress Snippets

Get Separate Count For Comments, Trackbacks, And Pingbacks In WordPress

Posted on August 19, 2025 By Admin No Comments on Get Separate Count For Comments, Trackbacks, And Pingbacks In WordPress

Get Separate Count For Comments, Trackbacks, And Pingbacks In WordPress

If you want to display or process separate counts for comments, trackbacks, and pingbacks in WordPress, the default comment count won’t suffice. WordPress lumps all these types together, making it hard to distinguish between genuine user comments and automated or external references like trackbacks and pingbacks. This tutorial shows you how to get accurate, separate counts for each type quickly and reliably.

Quick Fix

  1. Use WordPress’s get_comments() function with the type argument to fetch comments, trackbacks, or pingbacks separately.
  2. Create custom functions to return counts for each comment type.
  3. Add these functions to your theme’s functions.php file or a small custom plugin.
  4. Use these functions in your templates or blocks to display separate counts.

Why This Happens

WordPress stores comments, trackbacks, and pingbacks in the same database table (wp_comments) and by default, functions like get_comments_number() or comments_number() return a combined count. Trackbacks and pingbacks are types of comments but serve different purposes:

  • Comments: User-generated feedback or discussion.
  • Trackbacks: Notifications from other blogs linking to your post.
  • Pingbacks: Automated notifications from other WordPress sites linking to your post.

Separating these counts helps you better understand engagement and manage spam or external references more effectively.

When to Use Separate Counts

  • Displaying genuine user interaction separately from automated or external references.
  • Filtering or moderating comments, trackbacks, and pingbacks differently.
  • Creating custom reports or analytics on engagement types.
  • Improving UI/UX by showing distinct counts in post meta or widgets.

Updated Code for Modern WordPress

Modern WordPress (5.0+) supports querying comments by type using the get_comments() function with the type parameter. Below are three functions to get counts for comments, trackbacks, and pingbacks separately.

/**
 * Get count of approved comments for a post.
 *
 * @param int $post_id Post ID.
 * @return int Number of approved comments.
 */
function get_approved_comment_count( $post_id ) {
    $comments = get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='comment',
        'count'   =true,
    ) );
    return $comments;
}

/**
 * Get count of approved trackbacks for a post.
 *
 * @param int $post_id Post ID.
 * @return int Number of approved trackbacks.
 */
function get_approved_trackback_count( $post_id ) {
    $trackbacks = get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='trackback',
        'count'   =true,
    ) );
    return $trackbacks;
}

/**
 * Get count of approved pingbacks for a post.
 *
 * @param int $post_id Post ID.
 * @return int Number of approved pingbacks.
 */
function get_approved_pingback_count( $post_id ) {
    $pingbacks = get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='pingback',
        'count'   =true,
    ) );
    return $pingbacks;
}

How to Add This Code

Option 1: Add to Your Theme’s functions.php

  1. Open your active theme folder.
  2. Locate and open functions.php.
  3. Paste the above functions at the end of the file.
  4. Save the file and upload if editing locally.

Option 2: Create a Small Custom Plugin

  1. Create a new folder named comment-type-counts in wp-content/plugins/.
  2. Create a file comment-type-counts.php inside that folder.
  3. Paste the following code into that file:
<?php
/*
Plugin Name: Comment Type Counts
Description: Provides functions to get separate counts for comments, trackbacks, and pingbacks.
Version: 1.0
Author: Your Name
License: GPL2
*/

function get_approved_comment_count( $post_id ) {
    return get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='comment',
        'count'   =true,
    ) );
}

function get_approved_trackback_count( $post_id ) {
    return get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='trackback',
        'count'   =true,
    ) );
}

function get_approved_pingback_count( $post_id ) {
    return get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='pingback',
        'count'   =true,
    ) );
}
?>
  1. Activate the plugin from the WordPress admin dashboard.

Step-by-Step Test

  1. Ensure your posts have comments, trackbacks, and pingbacks approved.
  2. Open your theme’s single post template file (usually single.php or a template part).
  3. Insert the following code snippet where you want to display the counts:
<?php
$post_id = get_the_ID();

$comment_count = get_approved_comment_count( $post_id );
$trackback_count = get_approved_trackback_count( $post_id );
$pingback_count = get_approved_pingback_count( $post_id );
?>

<div class="comment-type-counts">
    <p>Comments: <?php echo esc_html( $comment_count ); ?></p>
    <p>Trackbacks: <?php echo esc_html( $trackback_count ); ?></p>
    <p>Pingbacks: <?php echo esc_html( $pingback_count ); ?></p>
</div>
…
WordPress Snippets

Adding A Custom Field Automatically On Post/Page Publish

Posted on August 19, 2025 By Admin No Comments on Adding A Custom Field Automatically On Post/Page Publish

Adding A Custom Field Automatically On Post/Page Publish

When managing a WordPress site, you might want to add a custom field automatically whenever a post or page is published. This can help automate metadata insertion, improve content organization, or trigger custom workflows without manual input. This tutorial shows you how to add a custom field on publish in WordPress using modern, best-practice code that works with both classic and block editors.

When to Use This

  • Automatically tagging posts with metadata like source, author notes, or custom flags.
  • Adding default values to custom fields for SEO, analytics, or content management.
  • Triggering custom plugin or theme logic that depends on post meta.
  • Ensuring consistency across published content without relying on manual input.

Updated Code for Modern WordPress

WordPress provides hooks like save_post and transition_post_status to detect when a post is published. The recommended approach is to use save_post combined with checks for the post status to ensure the custom field is added only once on publish. This avoids duplicate or unnecessary updates.

Here’s a clean, modern example that adds a custom field named my_custom_field with the value published_value when a post or page is published:

function add_custom_field_on_publish( $post_id, $post, $update ) {
    // Avoid recursion and autosaves
    if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
        return;
    }

    // Only proceed if post status is 'publish'
    if ( $post-post_status !== 'publish' ) {
        return;
    }

    // Check if the custom field already exists to avoid overwriting
    if ( get_post_meta( $post_id, 'my_custom_field', true ) ) {
        return;
    }

    // Add the custom field
    add_post_meta( $post_id, 'my_custom_field', 'published_value', true );
}
add_action( 'save_post', 'add_custom_field_on_publish', 10, 3 );

How to Add This Code

You can add this code either directly to your theme’s functions.php file or create a small custom plugin. Both methods are straightforward:

Option 1: Add to functions.php

  1. Access your WordPress site files via FTP or hosting file manager.
  2. Navigate to wp-content/themes/your-active-theme/.
  3. Open functions.php in a code editor.
  4. Paste the code snippet at the end of the file.
  5. Save and upload the file back.

Option 2: Create a Small Plugin

  1. Create a new folder named auto-custom-field inside wp-content/plugins/.
  2. Create a file named auto-custom-field.php inside that folder.
  3. Paste the following code inside auto-custom-field.php:
<?php
/*
Plugin Name: Auto Custom Field on Publish
Description: Adds a custom field automatically when a post or page is published.
Version: 1.0
Author: Your Name
*/

function add_custom_field_on_publish( $post_id, $post, $update ) {
    if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
        return;
    }

    if ( $post-post_status !== 'publish' ) {
        return;
    }

    if ( get_post_meta( $post_id, 'my_custom_field', true ) ) {
        return;
    }

    add_post_meta( $post_id, 'my_custom_field', 'published_value', true );
}
add_action( 'save_post', 'add_custom_field_on_publish', 10, 3 );
  1. Save the file.
  2. Go to WordPress admin > Plugins and activate Auto Custom Field on Publish.

Step-by-Step Test

  1. Add the code via functions.php or activate the plugin.
  2. Create a new post or page in WordPress admin.
  3. Publish the post/page.
  4. Go to the post editor, open the “Custom Fields” panel (enable it via Screen Options if hidden).
  5. Verify that the custom field my_custom_field exists with the value published_value.
  6. Try updating the post; the custom field should not be overwritten or duplicated.

Block Themes & Gutenberg Notes

  • This method works regardless of whether you use the classic editor or Gutenberg block editor.
  • Block themes do not affect how post meta is saved; the save_post hook fires normally.
  • If you want to expose this custom field in the block editor UI, consider registering it with register_post_meta() for REST API support.
  • For example, to register the meta for Gutenberg:
function register_my_custom_meta() {
    register_post_meta( '', 'my_custom_field', [
        'show_in_rest' =true,
        'single' =true,
        'type' ='string',
        'auth_callback' =function() {
            return current_user_can( 'edit_posts' );
        },
    ]);
}
add_action( 'init', 'register_my_custom_meta' );

Common Pitfalls

  • Autosave and revisions: Always check for autosaves and revisions to prevent unintended meta updates.
  • Duplicate meta: Use get_post_meta() to check if the field already exists before adding.
  • Post status checks: Ensure the post is actually published before adding the field.
  • Cache issues: If you use object caching, clear caches to see changes immediately.
  • Custom post types: Modify the code if you want to target custom post types by checking $post-post_type.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Control panels: cPanel, Plesk, DirectAdmin
  • WordPress versions 5.0 and above (supports Gutenberg and classic editor)
…
WordPress 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

Showing Amount Of Comments A Comment Author Made

Posted on August 19, 2025 By Admin No Comments on Showing Amount Of Comments A Comment Author Made

Showing Amount Of Comments A Comment Author Made

When managing a WordPress site, you might want to display how many comments a particular comment author has made. This can add social proof, encourage engagement, or simply provide context to readers. The quick fix is to use a custom function that counts comments by author and then display that count alongside their comment.

Quick Fix: Count Comments by Author WordPress

  1. Add a custom function to your functions.php file or a small custom plugin that counts comments by the author’s email or user ID.
  2. Modify your comment template to display the count next to each comment author.
  3. Test to ensure the count updates correctly for each commenter.

Why This Happens

By default, WordPress does not show how many comments a user or guest commenter has made. This is because comments are stored individually without aggregation by author. To display the number of comments an author has made, you need to query the database and count comments associated with that author’s email or user ID.

This is especially useful for community sites, forums, or blogs with active discussions where recognizing frequent commenters adds value.

Step-by-Step: Updated Code for Modern WordPress

The following example uses WordPress core functions and best practices to count comments by author email (works for both logged-in users and guest commenters):

<?php
/**
 * Get the number of approved comments by a comment author.
 *
 * @param WP_Comment $comment Comment object.
 * @return int Number of approved comments by the author.
 */
function get_comment_author_comment_count( $comment ) {
    if ( ! $comment instanceof WP_Comment ) {
        return 0;
    }

    $author_email = $comment->comment_author_email;

    if ( empty( $author_email ) ) {
        return 0;
    }

    $args = array(
        'author_email'   => $author_email,
        'status'         => 'approve',
        'count'          => true,
    );

    $count = get_comments( $args );

    return (int) $count;
}
?>

To display this count next to each comment author in your theme’s comments.php or comment template part, add:

<?php
$comment_count = get_comment_author_comment_count( $comment );
if ( $comment_count > 1 ) {
    echo '<span class="comment-author-count">(' . esc_html( $comment_count ) . ' comments)</span>';
}
?>

How to Add via functions.php or a Small Plugin

  1. Open your active theme’s functions.php file or create a new plugin file (e.g., comment-author-count.php).
  2. Paste the get_comment_author_comment_count() function into the file.
  3. Modify your comment template to call this function and output the count as shown above.
  4. Save and upload the changes.

If you prefer a plugin, wrap the function in plugin headers like this:

<?php
/*
Plugin Name: Comment Author Comment Count
Description: Displays the number of comments a comment author has made.
Version: 1.0
Author: Your Name
License: GPL2
*/

function get_comment_author_comment_count( $comment ) {
    if ( ! $comment instanceof WP_Comment ) {
        return 0;
    }

    $author_email = $comment->comment_author_email;

    if ( empty( $author_email ) ) {
        return 0;
    }

    $args = array(
        'author_email'   => $author_email,
        'status'         => 'approve',
        'count'          => true,
    );

    $count = get_comments( $args );

    return (int) $count;
}
?>

Step-by-Step Test

  1. Ensure your site has multiple comments from the same author (same email address).
  2. Add the function to functions.php or activate your plugin.
  3. Edit your theme’s comment template (usually comments.php) to call get_comment_author_comment_count( $comment ) and display the count.
  4. Visit a post with comments and verify the count appears next to the author’s name.
  5. Try commenting again with the same email and refresh to see the count increase.

Block Themes & Gutenberg Notes

With the rise of block themes and Gutenberg, comments are often rendered via blocks or server-side rendering. To integrate this functionality:

  • If your theme uses the core/comment block, you may need to create a custom block variation or extend the comment rendering via render_callback in PHP.
  • Use the same get_comment_author_comment_count() function inside your block’s PHP render callback to output the count.
  • For block-based themes, consider creating a small plugin that hooks into comment rendering filters like comment_text or comment_author to append the comment count dynamically.

Common Pitfalls

  • Counting by email only: Guest commenters with different emails will be counted separately even if they are the same person.
  • Performance: Counting comments for every comment on a large site can cause performance issues. Consider caching results if needed.
  • Comment moderation: Only approved comments are counted to avoid showing counts for spam or pending comments.
  • Theme compatibility: Some themes heavily customize comment output; ensure you insert the code in the correct template file.

Works on

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Control Panels cPanel, Plesk, DirectAdmin
WordPress Versions 5.0 and above (modern block and classic themes)
Themes Classic PHP templates, Block themes with minor adjustments

FAQ

…
WordPress Snippets

Adding Classes to the Current Page Item in wp_nav_menu()

Posted on August 19, 2025 By Admin No Comments on Adding Classes to the Current Page Item in wp_nav_menu()

Adding Classes to the Current Page Item in wp_nav_menu()

If you want to add a custom class to the current menu item in WordPress navigation, you’ve come to the right place. By default, WordPress adds classes like current-menu-item to highlight the active page in menus, but sometimes you need to add your own classes for styling or JavaScript targeting. This tutorial shows you how to add class to current menu item WordPress easily and cleanly.

Quick Fix: Add a Custom Class to the Current Menu Item

  1. Hook into the nav_menu_css_class filter.
  2. Check if the menu item is the current page.
  3. Add your custom class to the array of classes.
  4. Return the modified classes array.

This approach works perfectly in modern WordPress and can be added to your functions.php or a small custom plugin.

Why You Should Add a Custom Class to the Current Menu Item

  • Custom Styling: Sometimes the default current-menu-item class isn’t enough for your CSS needs.
  • JavaScript Targeting: Adding a unique class makes it easier to target the current menu item with scripts.
  • Theme Compatibility: Some themes or page builders require specific classes for active states.
  • Better Control: You can add multiple classes or change the class name to fit your project.

When to Use This Method

  • You want to add a class beyond the default WordPress classes.
  • You are building a custom theme or child theme and need precise control over menu item classes.
  • You want to add JavaScript hooks or CSS animations to the current menu item.
  • You are not using block-based navigation or want a PHP-based solution.

Updated Code for Modern WordPress

The best way to add a class to the current menu item is by using the nav_menu_css_class filter. Here’s a clean, modern example:

function add_custom_class_to_current_menu_item($classes, $item) {
    if (in_array('current-menu-item', $classes, true)) {
        $classes[] = 'my-custom-current-class';
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class_to_current_menu_item', 10, 2);

This code checks if the menu item already has the current-menu-item class and appends your custom class my-custom-current-class.

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

To add this code, you can either place it in your theme’s functions.php file or create a small plugin.

Option 1: Add to functions.php

  1. Open your active theme folder.
  2. Locate and open functions.php.
  3. Paste the following code at the end:
function add_custom_class_to_current_menu_item($classes, $item) {
    if (in_array('current-menu-item', $classes, true)) {
        $classes[] = 'my-custom-current-class';
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class_to_current_menu_item', 10, 2);
  1. Save the file and refresh your site to see the changes.

Option 2: Create a Small Plugin

  1. Create a new folder inside wp-content/plugins called custom-current-menu-class.
  2. Create a file named custom-current-menu-class.php inside this folder.
  3. Paste this code into the file:
<?php
/*
Plugin Name: Custom Current Menu Class
Description: Adds a custom class to the current menu item.
Version: 1.0
Author: Your Name
*/

function add_custom_class_to_current_menu_item($classes, $item) {
    if (in_array('current-menu-item', $classes, true)) {
        $classes[] = 'my-custom-current-class';
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class_to_current_menu_item', 10, 2);
  1. Go to WordPress admin > Plugins and activate “Custom Current Menu Class.”
  2. Check your menu on the front end.

Step-by-Step Test

  1. Apply the code via functions.php or plugin as shown above.
  2. Go to Appearance > Menus and ensure your menu is assigned to a theme location.
  3. Visit your site’s front end and navigate to a page included in the menu.
  4. Inspect the menu item using browser developer tools.
  5. Look for the default current-menu-item class plus your custom class my-custom-current-class.
  6. Test your CSS or JavaScript targeting the new class.

Block Themes & Gutenberg Notes

With the rise of block themes and Gutenberg’s Navigation block, the way menus are rendered can differ:

  • Block Themes: The Navigation block outputs menus dynamically and may not use wp_nav_menu() filters.
  • Gutenberg Navigation Block: Custom classes for current items are handled internally or via block settings.
  • Workaround: For block themes, consider using wp_nav_menu_items filter or custom block styles.
  • Classic Themes: The method described here works perfectly for PHP-rendered menus.

Common Pitfalls

  • Class Not Appearing: Ensure your menu is properly assigned and the page is part of the menu.
  • Wrong Hook: Use nav_menu_css_class, not wp_nav_menu_items for adding classes to individual items.
  • Block Themes: This method may not work if your theme uses block-based navigation.
  • Cache Issues: Clear any caching plugins or server cache to see changes immediately.
  • Class Name Conflicts:
…
WordPress Snippets

Posts pagination

Previous 1 2 3 4 Next

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