Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress adding shortcodes in functions.php

Tags:

php

wordpress

I wanna add a shortcode in the functions.php from WordPress, so I can use my function in my site.

The problem is, obviously the shortcodes.php is included after the functions.php, so it gives me an error:

Call to undefined function add_shortcode

How can I add shortcodes in my functions.php?

like image 665
Xatenev Avatar asked Apr 15 '26 14:04

Xatenev


1 Answers

if you do not want to alter your theme's functions.php file (for obvious reasons) you have two options

  1. create a child theme and make a functions.php file with your shortcode in there. Wordpress will recognize this file and automatically include it for you and as long as there is no naming conflicts with other functions in your parent theme's functions.php

  2. create a new file, custom_shortcodes.php or something, with your custom shortcode in it and add it to your theme. then in your theme's functions.php, at the very end, add the line

    include 'custom_shortcodes.php';

this will allow you to edit your custom shortcodes without having to alter the themes functions.php. just know if you update your theme, you will have to add the above line back in to functions.php. Personally, i always use a child theme and then end up using the first method but either is acceptable.

a last option, and what solved @xatenev problem, is to create a plugin and add all of your shortcodes to the plugin. This makes your custom code 'portable' and allows you to use it on any theme you have installed without going into the theme folder and adding/changing files.

like image 147
celeriko Avatar answered Apr 17 '26 04:04

celeriko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!