Useful WordPress Code Snippets for Functions.php

Blog

Here’s some code that I often use in my WordPress sites that can just be inserted into your functions.php file.

I am not an advanced PHP or WordPress developer so most of these code snippets I have aquired from searching around the web.

This page is mostly for my own reference but hopefully it might aslo come in useful for others. I will try to continually update this list.

Exclude categories from WordPress Category Widget

This excludes categories from the WordPress Category Widget by ID.

// Exclude Categories from Category Widget
function exclude_widget_categories($args){
$exclude = ""; // Categories IDs to exclude. Add your category ID numbers here seperated by a comma
$args["exclude"] = $exclude;
return $args;
}
add_filter("widget_categories_dropdown_args","exclude_widget_categories");

Change the “Select Category” text on the WordPress Category Widget

This changes the “Select Category” label text on the WordPress Category Widget to a custom text of your choosing.

// Changes "Select Category" label on Category Widget
function ChangeSelectTitle($cat_args){
$cat_args['show_option_none'] = __('Select Custom'); // Change "Select Custom" to your desired text
return $cat_args;
}
add_filter('widget_categories_dropdown_args', 'ChangeSelectTitle');

Display on one category from the WordPress Archive Widget

Shows only one category plus child categories from the WordPress Archive Widget by ID.

// Display archives for only one category & children from archive dropdown.
function archive_filter_pre_get_posts( $query ) {
if ( $query->is_main_query() && ! is_admin() ) {
if ( is_date() ) {
$query->set( 'cat', '10' );
}
}
}
add_action( 'pre_get_posts', 'archive_filter_pre_get_posts' );

Excludes categories from the Category Widget

Excludes categories from the category widget by category ID.

// Exclude Categories from Category Widget
function exclude_widget_categories($args){
$exclude = "1,5"; // Categories IDs to exclude
$args["exclude"] = $exclude;
return $args;
}
add_filter("widget_categories_dropdown_args","exclude_widget_categories");

Excludes categories from the Category Widget

Changes the “Select Category” title on the Category Widget.

// Changes "Select Category" on the Category Widget
function ChangeSelectTitle($cat_args){
$cat_args['show_option_none'] = __('Select Therapy');
return $cat_args;
}
add_filter('widget_categories_dropdown_args', 'ChangeSelectTitle');

Adds a class to all paragraph tags

This adds a custom class to all paragraph tags.

// Adds a class to all paragraph tags
add_filter( 'the_content', 'p_class_content_filter' ,20);
function p_class_content_filter($content) {
$content = preg_replace("/([^<]*)(<\/p>)/i", "\$1 class='my-class'\$2\$3", $content);

return $content;
}

Category: Wordpress

No comment yet, add your voice below!


Add a Comment

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

Comment *
Name *
Email *
Website