Now that we´ve learned how to create a child theme and some other things and tricks related to WordPress child theme creation, it´s time to learn how to add functions to your WordPress child theme.
Actually this will be the first of a series of tutorials dedicated to that subject but to be fair I have to tell you that, strictly speaking, in this post we will not be really adding any new function to our child theme. Today we will add some CSS styling, but for the example I´ve prepared for this post we will need to interfere with WordPress functions to add that new styling.
More specifically, we´ll need to modify an existing function.
Our first goal
I wanted to start with a very simple example, so what I´m proposing here is just to modify the way in which meta information for a post is displayed in the Twenty Twelve theme.
We will be using the same child theme I created for my post A WordPress child theme made easy… and easier, which I´d called “New 2012 Child Theme”. I added a very simple post to that “Tutorial Test Site”, and it would originally look like this:
Let´s say that we want to change the styling of the meta information line (the final line that appears below the content: “This entry was posted…”). We are going to highlight it somehow, enclosing it in a box with a particular background color and a border, and we will also separate it from the “Edit” link that is shown at the end of that line when we are logged in.
Of course, anybody who is familiar enough with the Twenty Twelve theme might argue that we can do that just by adding some style rules to the already existing entry-meta
class, but that would affect also the “Edit” link and, anyway, we are just looking for a simple example to deal with functions.
To make it even more necessary to modify a function, we will also change the displayed text. Let´s say we want it to read “Article posted…” instead of “This entry was posted…”.
So we are going to create a functions.php file for our child theme.
Some interesting basics first
If we take a look to the functions.php file included in Twenty Twelve we will find a very interesting information in its header. Open that file with your favorite text editor (I personally recommend Notepad++) and you will see this at the very top:
I mean, it´s all explained over there! As it reads, our child theme´s functions.php file will be loaded before the parent theme’s functions.php, so the child theme functions would be used. What this means is:
- Unlike style.css, which overwrites the parent’s style.css, our child’s functions will complement or add to the functions of the parent theme.
- We should never define a new function in our child theme’s functions.php file with the same name used by an existing parent theme´s function, with the exceptions I will explain right now:
We can also read in that functions.php information header that certain functions of the Twenty Twelve theme have been coded keeping in mind that somebody may want to modify them by means of a child theme. These “plugable” functions are wrapped in a call like this:
1 2 3 4 5 |
if ( ! function_exists( 'twentytwelve_nice_function' ) ) : ... // some stuff - function declaration ... endif; |
So, the function twentytwelve_nice_function
(supposing it ever existed) would only be loaded by the parent theme if it didn´t already exist, i.e. if a function by the same name hadn´t been declared first by the active child theme.
Finally, if you are not familiar with filter and action hooks don´t worry, we won´t deal with them in the present post. We will use them in future tutorials of this series.
Creating our child theme´s functions.php file
Remember that the only required file to create a child theme is style.css. The functions.php file could not exist at all in our child theme if we don´t need to add or modify any function, or it could even exist but be empty.
So, to create a brand new functions.php we will only need to do exactly that: create an empty file and save it in our child theme folder with the name “functions.php”.
Open your text editor, type the opening and closing php tags, save that file as “functions.php” and upload it to your child theme folder and you will have your first functions file. But we don´t want it empty, do we?
Of course not. But, for the time being, we will create a functions.php file with just one function. The particular function we will need to modify for our example is called twentytwelve_entry_meta. The first thing to do is to identify that function in the original functions.php file included in Twenty Twelve, copy it and paste it on a new empty file in our text editor, between opening and closing php tags. Since this is one of the plugable functions we mentioned before, it begins with if(!function_exists('twentytwelve_entry_meta')):
and ends with endif;
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?php function twentytwelve_entry_meta() { // Translators: used between list items, there is a space after the comma. $categories_list = get_the_category_list( __( ', ', 'twentytwelve' ) ); // Translators: used between list items, there is a space after the comma. $tag_list = get_the_tag_list( '', __( ', ', 'twentytwelve' ) ); $date = sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><time datetime="%3$s">%4$s</time></a>', esc_url( get_permalink() ), esc_attr( get_the_time() ), esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ) ); $author = sprintf( '<span><a href="%1$s" title="%2$s" rel="author">%3$s</a></span>', esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ), esc_attr( sprintf( __( 'View all posts by %s', 'twentytwelve' ), get_the_author() ) ), get_the_author() ); // Translators: 1 is category, 2 is tag, 3 is the date and 4 is the author's name. if ( $tag_list ) { $utility_text = __( 'This entry was posted in %1$s and tagged %2$s on %3$s<span> by %4$s</span>.', 'twentytwelve' ); } elseif ( $categories_list ) { $utility_text = __( 'This entry was posted in %1$s on %3$s<span> by %4$s</span>.', 'twentytwelve' ); } else { $utility_text = __( 'This entry was posted on %3$s<span> by %4$s</span>.', 'twentytwelve' ); } printf( $utility_text, $categories_list, $tag_list, $date, $author ); } endif; ?> |
We are going to modify that function now. Remember that we just want to add some styling to the post meta information line and also change some wording on the line text.
We will create a new division for the printf($utility_text, $categories_list, $tag_list, $date, $author)
function that we will find near the end (it is the PHP function that produces the formatted string for the post meta information line). We will give that new div an appropriate ID name, for example: child-custom-meta
. Then we will change the text “This entry was posted” by “Article posted” (you will find this piece of text in the declarations of the variable $utility_text
). Finally save your functions.php file, which now should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<?php if ( ! function_exists( 'twentytwelve_entry_meta' ) ) : /** * Prints HTML with meta information for current post: categories, tags, permalink, author, and date. * * Create your own twentytwelve_entry_meta() to override in a child theme. * * @since Twenty Twelve 1.0 */ function twentytwelve_entry_meta() { // Translators: used between list items, there is a space after the comma. $categories_list = get_the_category_list( __( ', ', 'twentytwelve' ) ); // Translators: used between list items, there is a space after the comma. $tag_list = get_the_tag_list( '', __( ', ', 'twentytwelve' ) ); $date = sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s">%4$s</time></a>', esc_url( get_permalink() ), esc_attr( get_the_time() ), esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ) ); $author = sprintf( '<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s" rel="author">%3$s</a></span>', esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ), esc_attr( sprintf( __( 'View all posts by %s', 'twentytwelve' ), get_the_author() ) ), get_the_author() ); // Translators: 1 is category, 2 is tag, 3 is the date and 4 is the author's name. if ( $tag_list ) { $utility_text = __( 'Article posted in %1$s and tagged %2$s on %3$s<span class="by-author"> by %4$s</span>.', 'twentytwelve' ); } elseif ( $categories_list ) { $utility_text = __( 'Article posted in %1$s on %3$s<span class="by-author"> by %4$s</span>.', 'twentytwelve' ); } else { $utility_text = __( 'Article posted on %3$s<span class="by-author"> by %4$s</span>.', 'twentytwelve' ); } ?> <div id="child-custom-meta"> <?php printf( $utility_text, $categories_list, $tag_list, $date, $author ); ?> </div> <!-- end #child-custom-meta --> <?php } endif; ?> |
Adding some style
The last thing we need to do is to add the CSS rules for the new child-custom-meta
div. Open your style.css file (the stylesheet of your child theme) and add background color, some padding, the border thickness and color and some bottom margin. Let´s for example add these lines at the bottom of style.css:
1 2 3 4 5 6 |
#child-custom-meta { background: #f0eac0; padding: 10px; border: 1px solid #ad8e55; margin-bottom: 15px; } |
We are all set now. Upload the new functions.php file and the modified style.css to your child theme folder, and you will see the results:
Conclusion
In this post we have learned the basics about adding new functions to a child theme. Although we didn´t create any new functions, we have been able to modify some functionalities by means of our child theme´s functions.php file, customizing the default output of the Twenty Twelve theme.
We will create a brand new function in the next tutorial of this series.
As always, I would be glad to know about your feelings and your progress through the comments!
- Brave Browser – Will the new player be able to change the game rules? - 31 May, 2019
- All Top Ten WordPress themes are premium now - 18 December, 2017
- Child Theme Detection Just Got Better - 17 January, 2017
Thank you so much! this is exactly what I wanted! 😀
Thank you! SO very helpful!
Adding to the other two comments: Thank you! As a php novice I’ve been trying to figure out how to edit that meta data all day to add in a function call to output the word count. This was the first article I found (and I read quite a few) that actually helped. It was splitting the function into two separate php sections that finally allowed me to add what I needed without the white screen of death. So, thank you again for the clear, very helpful instructions. 🙂
Always glad to help, Cathy. Thank you for your kind words.
I’ve made the changes but it doesn’t override the parent function. can you help me?
Hi Shahab,
It should work if you followed all the steps. Unfortunately, there´s no way for me to tell you what could have gone wrong without having more details about your case.
Something you could do in order to check if the child´s functions.php file and the function itself are working is the following: make a copy of the complete parent theme´s functions.php file and save it side by side with the original (for example renaming it as original_functions.php), then remove the twentytwelve_entry_meta() function from the original parent theme´s functions.php and check what happens. If your meta information line is not appearing at the end of your posts, there is something wrong with your child´s functions.php or the function contained in it. Check them and look for your error but, to leave things as they were before testing, you should delete the modified functions.php file in your parent theme´s folder and change the name of the backup copy you made from original_functions.php back to functions.php.
I hope this helps.
Thank you so much for reply. I found out that name of function file was wrong and when I corrected that it worked.
I´m glad you solved it.
Thank you, this is a great article for working with the functions.php in theme child! Rewrite an existing function is easy but wha’ts going on when the theme parent is updated?
Nothing. You´ll have no problems since your child theme function will still work after the parent theme update (that´s the beauty of child themes!).
I can only think of a couple of cases where you may encounter possible problems:
a) For whatever reason, the function being called by the updated parent theme has changed its name. The solution in this case is obvious: change the name of your function accordingly.
b) The original function used WordPress function(s) which had been deprecated. In this case you should check the new parent theme function which substitutes the one you rewrote, and then modify your child theme function in the same manner.
So in a nutshell, I can create a functions.php, single.php, etc., in the child theme and modify only the parts I need to from the original functions.php, single.php, etc. and the remainder (whatever I did not modify) will be inherited? I’m confused on whether all of the file’s code needs to be copied over to the child file or if I only need to copy the code I wish to modify and the rest is inherited.
Thanks!
Not exactly, Ren
It´s not the same for functions.php than for a page template (like single.php). Let me explain this:
– In the functions.php of your child theme you can include only your new functions or the functions that you´re modifying for your child theme. The rest of the functions will still be loaded by WordPress from the parent´s functions.php file, only that some of them will be overriden by those of your child theme that have the same function name. I other words: you don´t have to copy all the code from the parent theme´s functions.php, but just add what you need to your child´s functions.php.
– In the case of a template like single.php or template parts such as footer.php, where the code must follow a particular flow order or timeline, WordPress will load the complete file found in the child theme to define the template, so the corresponding file in the the parent theme will be overriden. In other words: In this case you should copy the entire template php file (with the same name) into your child theme folder, and then modify whatever you want over that new file.
In many cases you could also modify the behavior of templates without modifying or copying the template files by using WordPress hooks, but we will see them on the next tutorial of this series.
Also, if instead of the general templates you would like to modify some particular template like a blog page or a gallery page, you can also add in your child theme a new template with a different name.
For example, let´s say your parent theme has a gallery page and you want to make your own gallery page template somewhat different from it (or even make a completely new one from scracht). You can copy the original file to your child theme folder (or create a new file in that folder if you´re making it from scratch) and give whatever name you want. Let´s say you name it “rengallery.php”, you can make the first lines of your new file look like this:
Now when you´re creating a new page in your WordPress Admin Area, under “Page Atributes” you would have the chance to choose “Ren New Gallery” as one of the available page templates. It´s that easy.
I hope this helped you clarify things. If you still have any doubt, don´t hesitate to ask again.
Thanks a lot Luis. You cleared everything up for me. I appreciate such detailed response.
You´re welcome, Ren.
Now that you know how to make your own page templates, go ahead and experiment with them, it´s fun! Plus you´ll still have the original templates without the need to switch back to your parent theme, in case you want to compare them or even to use both of them on different pages if that suits you. 🙂
Great tutorial, but I’d like to change a non-pluggable function that does not have an if endif. How is that achieved? Many thanks in advance 🙂
Ah, just read your most recent tutorial. Sounds like I need to wait until the one about create filters…
Yep. You didn´t allow me the time to reply, Josef.
During the last few minutes I was having a hard time thinking: how am I going to tell this guy he should wait, specially when I´m not having the time to post tutorials as frequently as I would like to?.
Nobody wants to wait for things like this. You want to customize your theme, now! don´t you?
So I invite you to let me know the changes you need, and I´ll try to give you a hint about it. You can either reply to this comment or send me an email through our contact page, whatever you prefer.
Thanks for the tips 🙂 Quite helpful!
very helpful article, thanks
My parent theme has a page I want to edit called page-header.php and pulls into the function.php by require_once( get_template_directory() .’/page-header.php’ );
How would I edit this page from my child theme?
Hi Jeff,
You should do two things:
1. Make a copy of page-header.php, place it in your child theme´s folder and make whatever modifications you want to it, without ever changing the original file that remains in your parent theme.
2. That “require_once” is calling your parent´s page-header.php, so your customization to the child´s page-header.php wouldn´t work unless you do something else: Create a functions.php in your child theme´s folder (if you don´t have one yet) and add the following line to it:
require_once( get_stylesheet_directory() .’/page-header.php’ )
Dear Mr. Luis
I am using twentyfourteen-child theme as child theme.
I have style.css
header.php
functions.php in the twentyfourteen-child folder
in order to get child theme header.php working i used require_once( get_stylesheet_directory() .’/page-header.php’ )
it gave error that file with such name is not found
i tried it as require_once( get_stylesheet_directory() .’/header.php’ ); also
but i am getting same error
Following is code of my functions.php file
I am using this for a website with url : http://christianreview.ca/
Please help
Thanks in advance
Gulzar
Hello Luis, thank you very much for this great tutorial.
Something is not clear for me:
functions.php describes which functions exist and style.css how they look. In this example: how does the template know that child-custom-meta has to be loaded in that particular place? child-custom-meta is now going to be loaded everywhere where function twentytwelve_entry_meta() is loaded right?
I am going to check your next tutorial now…
Again, thank you. Regards, Felix
This could be an irrelevant comment and I’m sorry – but the character that appears throughout the post in place of apostrophes is not an apostrophe and cannot be used like that.
Thanks for the great series here.
I do have one eager question though. Assuming you first opened single.php to look for how the post meta was displayed and maybe to see if you could edit the content there (but since you cant).. how were you able to trace it to functions.php and more specifically, the actual function “twentytwelve_entry_meta()”, which is responsible for that meta output?
If you hadn’t any prior knowledge knowing that this function produced that meta content, how else would you find your way to that function?
Very curious to know.
Thanks so much.
Hi Mario,
That´s a good question, but the answer is really quite simple.
As you said, you won´t find that function in single.php, but the content is there. Where? Take a look at the structure of single.php:
get_header();
…some code
……get_template_part( ‘content’, get_post_format() );
…more code
get_sidebar();
get_footer();
Inside the loop this file is calling a template file: content.php. If you open that file, you will find twentytwelve_entry_meta() is there. So the next thing to do would be to look for that functions in functions.php.
When I was a kid I had a teacher who used to organize his classes as a general open discussion about the topic he wanted to teach that day (the subject was economics and politics). And he would rate not only the good answers from the students, but also all the questions. I would give your question a high rating, Mario. Being curious is the best way to learn. 🙂
Thanks so much for the quick and informative reply, Luis! and I appreciate the commendation on my comment 🙂 Being curious is exactly what provoked it.
So, knowing that ‘content’ refers to ‘content.php’, I am now able to successfully trace the meta content from single.php right to the twentytwelve_entry_meta() function in functions.php.
I feel that becoming efficient with locating the definition of a function specific to the content you are trying to modify is a great thing to know when customizing your themes.
This technique will definitely come in handy when trying to alter the content in other areas. Much better than taking the easy way out and just styling the whole block from within single.php (which would also style the ‘edit’ link).
Looking forward to more great posts, Luis.
Best,
Mario
You´re welcome, Mario.
Please note that ‘content‘ does not necessarily or strictly refers to content.php, although it does in that context.
It is used in the
get_template_part()
function, which accepts two parameters:get_template_part( $slug, $name )
The ‘$slug‘ is the generic template file (in this case, ‘content‘), while ‘$name‘ is optional and refers to the name of a specialized template (which in this case is called dynamically by the
get_post_format()
function, therefore depending of the type of post).So if for example you find something like
get_template_part( 'content', 'gallery' )
, then you should look for a specific template file named ‘content-gallery.php‘.Wow.. thank you very much for the clarification on that. Now I feel better equipped to identify which template file is being called by the get_template_part function. Excellent information, Luis. Thank you very much for taking the time to reply in such detail. I’m sure this will help many other alike 🙂
Dude – thank you SO much for this! I have been looking everywhere for this exact same thing through WordPress and other sites and it’s a straight up cluster-f.
Thanks again!!!
Thanks! Learning how to add PHP functions is a big step up for me. This post boiled it down to the essentials and didn’t make poor assumptions about what I needed to know. It is always a good day when you learn something new!
Hello there..really usefull article series..I do appreciate your efforts a lot!!!And definately thumbs up for your solid, documented, comments’ feedback…The teacher you mention above while answering Marios’ question seems he did a great job finally.. 🙂
I’m going to do a lot of reading in the next few days…what a wonderfull site. As a newbee to wordpress i’m crawling the internet for answers. I was searching for a way to translate “leave a comment” on my blog page (language = Dutch), and found that changing the comments.php was a solution. But when the theme is updated, i think that my changes will be overwritten. Can i make a comments.php in my child theme with only the function for “leave a reply”?
Thanks for this great tutorial
This is very informative…
But i am a little confused on the page template child theme. For example, if we were to modify the page.php page template, we copy all the original code from parent’s page.php and paste it into our child theme folder and modify from child theme. By this way, the parent file will be overwritten. So, what if there is a theme update later on parent’s page.php by the theme author? As we already have our modified child page.php file earlier, any new updates on parent’s page.php will not be taken into account anymore?
How do we manage such situation? Thanks!
The purpose of the child theme is to maintain YOUR custom styles and code through parent theme updates. Your child theme will still get updates as your functions.php and style.css are just appended or simultaneously loaded to your parent themes files. So that covers the most important updates that your theme would probably receive and since you’ve probably tweaked the style of your theme anyways, even if they made changes to the core style of the parent theme you wouldnt want them. But if they did (unlikely) and you do want them, you could just re-make your child theme templates to include whatever new features they added (and only the ones you want). So win-win-win all around.
Great post for like us newbies. Thanks Luis 🙂
Regards Salekin
Very wonderful way to explain the concept. I was searching for this. Can you have a post on how to add customization via add option via admin page.. Once I added the code , next time if I want to do it from Admin page option, can I add some text-box in admin page to take valve from there and modify the value. Although I more demanding.. please feel free to deny if it is more complected.
Thanks Luis Alejandre for yet another awesome post, Your blogs are very helpful for a newbie blogger. I am still in the process of learning. It is really good that I subscribed on your website.
Thank you so much.
i use genesis framework and I need more code to customize the appearance and functions. There is a bit different..
How can I create functions.php for accelerate_child theme?
Thanks Luis for this super guide..!
Thanks, usefull for website making.
I was able to create a child functions.php which only contains the “”
I want to alter of eliminate the code which image size for featured images which I find in the twentytwelve setup function:
“// This theme uses a custom image size for featured images, displayed on “standard” posts.
add_theme_support( ‘post-thumbnails’ );
set_post_thumbnail_size( 624, 9999 ); // Unlimited height, soft crop”
I can’t figure out how this is done. Please give me some help of advise where to look for documentation.
This is a great guide. I’m using genesis framework and want to add some changes. Does this same applies for genesis.
Thanks for sharing!
Hello Luis,
Feel great to read your another wonderful blog post.I’m a regular follower of your blog & glad to see you come up with so informative write up.All the time I learn so many things from your writing.Wait for your next one and good wishes for you.
Thank You
Very informative article,
thanks for sharing the amazing post
Thanks, usefull for website making.
Thanks Luis, for this great tutorial!
It already helped me a lot.
But I do have 1 question;
I want to modify a function from the parent theme, but it starts with
if (!function_exists(‘project_single_control’)) {
function project_single_controls() {
I’ve been checking other php files to see if there is a project_single_control or project_single_controls, but I can’t find it.
And I also don’t understand the fact that in the first lines it’s ‘control’ and in the second ‘controls’
So I don’t know what to do now, can you please help me?
Thanks in advance!
Hi, Eefke.
That for sure is an error. A pluggable function should have the same function name in both places, as you can see in the WordPress Codex.
Hi
Can we add this function to parent theme as well? or child theme is necessary?
I am amazed to see that this article were published in 2013 & its still a good resource for adding the functions in a WordPress child theme.
Thanks for the informative solution Luis.
This is probably the best , most concise step-by-step guide I have ever seen on how to add function wordpress
i use genesis framework and I need more code to customize the appearance and functions. There is a bit different..
Hi
I have tried to make changes to the functions.php file based on above and it doesn’t seem to be working and if you could help I’d really be thankful.
There is a setup function (pasted below) with a custom header item in it and I need to extend the height. I copied it from the if function to end if and made the small change to the args
// Custom header
$args = array(
‘width’ => 1440,
‘height’ => 221, ————–(
‘default-image’ => get_template_directory_uri() . ‘/images/header.jpg’,
‘uploads’ => true,
‘header-text’ => false
);
add_theme_support( ‘custom-header’, $args );
my functions file, as per wordpress codex also has this piece of code at the top
add_action( ‘wp_enqueue_scripts’, ‘my_theme_enqueue_styles’ );
function my_theme_enqueue_styles() {
wp_enqueue_style( ‘parent-style’, get_template_directory_uri() . ‘/style.css’ );
}
The setup function:
if ( ! function_exists( ‘baskerville_setup’ ) ) {
function baskerville_setup() {
// Automatic feed
add_theme_support( ‘automatic-feed-links’ );
// Post thumbnails
add_theme_support( ‘post-thumbnails’ );
add_image_size( ‘post-image’, 945, 9999 );
add_image_size( ‘post-thumbnail’, 600, 9999 );
// Post formats
add_theme_support( ‘post-formats’, array( ‘aside’, ‘audio’, ‘chat’, ‘gallery’, ‘image’, ‘link’, ‘quote’, ‘status’, ‘video’ ) );
// Custom header
$args = array(
‘width’ => 1440,
‘height’ => 221,
‘default-image’ => get_template_directory_uri() . ‘/images/header.jpg’,
‘uploads’ => true,
‘header-text’ => false
);
add_theme_support( ‘custom-header’, $args );
// Add support for title_tag
add_theme_support( ‘title-tag’ );
// Set content width
global $content_width;
if ( ! isset( $content_width ) ) $content_width = 676;
// Add support for custom background
$args = array(
‘default-color’ => ‘#f1f1f1’
);
add_theme_support( “custom-background”, $args );
// Add nav menu
register_nav_menu( ‘primary’, __( ‘Primary Menu’, ‘baskerville’ ) );
// Make the theme translation ready
load_theme_textdomain( ‘baskerville’, get_template_directory() . ‘/languages’ );
}
add_action( ‘after_setup_theme’, ‘baskerville_setup’ );
}