How to limit the number of category links displayed in a WordPress post content

To limit the number of category links displayed in a WordPress post content, you can create a custom function and use the the_content filter to modify the post content accordingly. Add the following code snippet to your theme’s functions.php file:

  1. In your WordPress admin dashboard, go to “Appearance” > “Theme Editor.”
  2. In the right sidebar, locate and click on the “functions.php” file.
  3. Add the following code snippet at the end of the file:
function limit_category_links_in_post_content($content) {
// Set the maximum number of category links to display
$max_categories = 3;

// Get the post categories
$categories = get_the_category();

// If there are more categories than the maximum allowed, limit the list
if (count($categories) > $max_categories) {
$categories = array_slice($categories, 0, $max_categories);
}

// Generate the category links
$category_links = array();
foreach ($categories as $category) {
$category_links[] = '<a href="' . esc_url(get_category_link($category->term_id)) . '" title="' . esc_attr($category->name) . '">' . $category->name . '</a>';
}

// Add the category links to the post content
$content .= '<p class="post-categories">Categories: ' . implode(', ', $category_links) . '</p>';

return $content;
}
add_filter('the_content', 'limit_category_links_in_post_content');

This code snippet creates a function called limit_category_links_in_post_content() that modifies the post content to include a limited number of category links. You can change the $max_categories variable to set the maximum number of category links to display.

  1. Click “Update File” to save the changes.

Now, the category links displayed in the post content will be limited to the specified maximum number.

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Leave a Reply

Your email address will not be published. Required fields are marked *