Custom WordPress Code: PHP Snippets
Let’s explore some detailed tricks to enhance our website’s security and functionality by adding custom WordPress code to the function.php file in WordPress. This will simplify our lives.
Brief introduction: This guide is intended for individuals who already have a basic understanding of WordPress and PHP programming, which is a bit more complex than HTML mark-up (after all, one is for “creating things” while the other is for “laying out content“).
The distinction between editing HTML and PHP can be simply put like this:
If you err while editing HTML, your content will appear unattractive. If you err in PHP, your site might crash!
Naturally, we can incorporate some of these functionalities by using a WordPress plugin, but as you can see, we can steer clear of adding software that makes our site slower and more cumbersome .
What is the function.php file?
The function.php file is a crucial component of WordPress, containing specific functions utilized by the active theme we have chosen.
Each theme comes with its own function.php file, and switching to a different theme means we will be using a different set of functions. Generally, we add our custom functions to this file to modify how the theme behaves.
You can find references to the function.php file on the official WordPress website .
Where can I find the function.php file?
The function.php file can be found in the root directory of every WordPress theme. To determine which file requires modification, we must first identify the theme currently in use. Therefore, we navigate to the administration menu and select Appearance > Themes to check which of the installed themes on our CMS is currently active.
Once we know the active theme on our WordPress site, let’s access our server through FTP. We can locate the file at the following path (note that it may vary in some instances): www.example.com/wp-content/themes/Newspaper-child/
How to Safely Edit the Function.php file
To prevent irreparable damage, I suggest the following:
- Conduct all tests on a local copy of your site or on an online test version;
- Prior to making any changes, create a backup of our function.php file;
- Access your server via FTP and refrain from making changes through the WordPress admin panel (if desired, you can edit the file from Appearance > Editor);
- Make modifications to the function.php file of the child theme rather than the original theme, as changes to the original theme’s function file will be lost during theme updates;
- Select an editor that at least provides syntax highlighting (though the following codes are quite simple and could also be edited with basic tools like Notepad);
function.php: code tricks
Once we grasp the importance of working safely, let’s explore some functionalities we can utilize with this file. Many of these are genuine techniques that can enhance the work of a web developer or an SEO consultant. Therefore, considering the various professions, I have categorized these micro tutorials into two distinct sections.
Some of the suggested codes are functions that are automatically triggered across all our pages using WP filters ( add_filter ), while others are activated only through specific actions ( add_action ). In certain instances, we will also examine straightforward functions that need to be invoked in particular areas of our theme. In such cases, we will need to call them from within other files.
Aside from one script, I have gathered all the others from various sources over the years, and I will include references whenever possible.
All these scripts are compatible with the latest version of WordPress, 4.61 .
Codes from developers
The scripts listed below can assist programmers and webmasters in building websites by modifying various graphic and coding elements of different WordPress installations, allowing for customization of the visual and structural features of the CMS.
Change the appearance of the tag cloud
To change the font size and line spacing, sorting and number of elements in our site’s tag cloud we can use the following function:
function my_tag_cloud_args($in){
return "smallest=9&largest=26&number=80&orderby=name&unit=px&order=RAND";
}
add_filter( "widget_tag_cloud_args", "my_tag_cloud_args" );
From the code, it’s clear that we can establish the following for our tag cloud:
- The font sizes for the least utilized tags (smallest);
- Â The font sizes for the most utilized tags (largest);
- The total number of tags to display (number);
- Â The sorting method (name, which organizes by name, or count, which organizes by the number of posts linked to the tag);
- The unit for font sizing (unit: px, em, pt, or %);
- The order in which they appear (random RAND, ascending ASC, descending DESC).
Change the logo for the admin login
To personalize the login page for users registered on our WordPress multi-user site, we don’t require any specific plugins; just a few lines of code in the function.php file will suffice.
function custom_login_logo() {
echo '<style type="text/css">h1 a {
background-image: url(<?php echo get_stylesheet_directory_uri();Â ?>/images/logo-login.png);!important; }</style>';
}
add_action('login_head', 'custom_login_logo');
In this example our function will replace the classic WordPress logo with an image inside the images folder of the theme we have active.
Adjust the amount of text shown in the excerpt
Using this code, we can determine how much text appears when looking at a post preview summary box (typically featuring the title, image, category, author, and a portion of the text).
function custom_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'custom_excerpt_length');
In particular, this function limits the content of the introductory text of the article to 20 words . Changing this value will change the amount of text displayed.
Hide WordPress version in use from header
Given that we can find out the version of WordPress in use on a site in other ways, to make it more complicated to access this information, simply add the following function to the function.php file
function wp_remove_version() {
return '';
}
add_filter('the_generator', 'wp_remove_version');
Automatically update copyright dates
To safeguard our content and prevent unauthorized copying, it is essential to state that it is protected by copyright. Furthermore, we must specify the duration for which this protection is applicable.
To eliminate the need for annual updates to this information, we can implement a dynamic display of this data.
The script below will fetch the date of the earliest content and the date of the most recent post.
function dinamic_copyright() {
global $wpdb;
$copyright_dates = $wpdb->get_results("SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM $wpdb->posts WHERE post_status = 'publish'");
$output = '';
if($copyright_dates) {
$copyright = "© " . $copyright_dates[0]->firstdate;
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
$copyright .= '-' . $copyright_dates[0]->lastdate;
}
$output = $copyright;
}
return $output;
}
After inserting this script into the function.php file, it’s advisable to execute it at the desired location, typically at the end of the footer.
For instance, I accessed my footer.php file (having previously made a copy in the child theme) and included, at the chosen spot for displaying this date range,<?php echo dinamic_copyright(); ?>
Incorporating images into feeds
To enhance the look of our feeds, customizing their appearance to make them more visually appealing and linking the relevant featured image to our news, or if we aim to develop an automated newsletter that periodically selects and sends the latest published articles to recipients, we need to implement a specific function in our function.php file.
function featuredtoRSS($content) {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'medium' ) . '</figure>' . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'featuredtoRSS');
add_filter('the_content_feed', 'featuredtoRSS');
Valuable SEO Functions
The following code can assist anyone looking to enhance the SEO of their WordPress website, thereby improving user experience and boosting search engine rankings.
Remove URL Field from Comments
If you notice that numerous individuals are misusing the comments section of your articles to promote certain websites, a great way to enhance comment quality is to remove the URL field.
add_filter('comment_form_default_fields', 'unset_url_field');
function unset_url_field($fields){
if(isset($fields['url']))
unset($fields['url']);
return $fields;
}
If it is really necessary for the user to insert a link to explain some concept, he can always put it in the message they send you.
Removing pages/posts from search results
When we need to exclude certain pages or posts from the search results accessible to users, we can implement the following function.
function SearchFilter($query) {
if ($query->is_search) {
$query->set('post__not_in', array(23,44,33,666));
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
To find the unique ID that identifies each page/post, I direct you to a previous article of mine.
This feature is quite useful if we prefer that users do not access service pages, thank you pages, or remarketing campaign landing pages.
Display content seniority or freshness
If we wish to inform our users about which contents have been recently updated or which have remained unchanged for an extended period, we can automate this process using a script.
Adjust the quality of images (and their size)
Starting with the premise that the size of a graphic file should be minimized at the source, utilizing photo editing software, we can select the quality at which it will be saved among our media in WordPress.
The code is as follows:
add_filter( 'jpeg_quality', create_function('', 'return 100;' ));
In this example, images will be loaded with a compression factor of 100%, and by adjusting this parameter, we can reduce the quality to lower values ( 90%, 80% ).
Insert Google Analytics Tracking Code
If our theme does not allow for the addition of the Google Analytics tracking code or any other specific code that needs to be placed in the header of every page on our site, we can add the script to connect GA directly from the function.php file without needing to modify the header.php file.
function add_google_analytics() {
echo "<script>";
echo "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){";
echo "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),";
echo "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)";
echo "})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');";
echo "ga('create', 'UA-XXXXXXXX-X', 'auto');";
echo "ga('send', 'pageview');";
echo "ga('set', 'anonymizeIp', true);";
echo "</script>";
}
add_action('wp_head', 'add_google_analytics');
Certainly, you must substitute UA-XXXXXXXX-X with your Analytics account ID, and as you can observe, I have already provided the code above that adheres to the Italian cookie regulations.
Modify the name of the guest post author
If your website features multiple Guest Posts, you don’t need to create a new user each time you publish one. Instead, you can utilize this feature to insert a custom field in the post associated with the guest post, where you can specify the author’s name.
function guest_author_name( $name ) {
global $post;
$author = get_post_meta( $post->ID, 'guest-author', true );
if ( $author )
$name = $author;
return $name;
}
add_filter( 'the_author', 'guest_author_name' );
add_filter( 'get_the_author_display_name', 'guest_author_name' );
The custom variable to be included in the article whose author name you wish to modify is referred to as guest-author
, and its value should be the name of the author of the guest post.
If you need any WordPress custom coding for you website, please don’t hesitate to get in touch!