Imagine poder añadir cosas nuevas a su sitio web WordPress, como presentaciones de diapositivas, formularios de contacto o incluso listas especiales, con sólo teclear un simple código. Ese es el poder de los shortcodes.
Verás que muchos plugins y temas de WordPress pueden usar shortcodes para añadir características extra a tu sitio. Muchos de nuestros lectores nos preguntan cuál es la mejor forma de añadirlos a sus entradas, páginas y barra lateral.
En este artículo, te mostraremos cómo utilizar shortcodes en tu sitio web WordPress, paso a paso. Incluso te mostraremos cómo crear shortcodes personalizados si quieres ser realmente creativo.
¿Qué son los shortcodes?
Los shortcodes en WordPress son atajos de código que le ayudan a añadir contenido dinámico a entradas, páginas y widgets de la barra lateral de WordPress. Se muestran dentro de corchetes como estos:
[myshortcode]
Para entender mejor los shortcodes, echemos un vistazo a los antecedentes de por qué se añadieron en primer lugar.
WordPress filtra todo el contenido para asegurarse de que nadie utiliza las entradas y el contenido de las páginas para insertar código malintencionado en la base de datos. Esto significa que puedes escribir HTML básico en tus entradas, pero no puedes escribir código PHP.
Pero, ¿y si quisieras ejecutar algún código personalizado dentro de tus entradas para mostrar entradas relacionadas, banners publicitarios, formularios de contacto, galerías o cualquier otra cosa?
Aquí es donde entra en juego la API de shortcode.
Básicamente, permite a los desarrolladores añadir su código dentro de una función y luego registrar esa función con WordPress como un shortcode, para que los usuarios puedan utilizarlo fácilmente sin tener ningún conocimiento de codificación.
Cuando WordPress encuentre el shortcode, ejecutará automáticamente el código asociado a él.
Veamos cómo añadir shortcodes fácilmente a tus entradas y páginas de WordPress. Puede utilizar los siguientes enlaces para saltar a su método preferido.
- Adding a Shortcode in WordPress Posts and Pages
- Adding a Shortcode in WordPress Sidebar Widgets
- Adding a Shortcode in Old WordPress Classic Editor
- Adding a Shortcode in WordPress Theme Files
- Adding a Shortcode in Block Theme Files With the Full-Site Editor
- Creating Your Own Custom Shortcode in WordPress
- Shortcodes vs. Gutenberg Blocks
Añadir un shortcode en entradas y páginas de WordPress
En primer lugar, es necesario editar la entrada y la página en la que desea añadir el shortcode.
Después, tienes que hacer clic en el botón añadir bloque ‘+’ para insertar un bloque shortcode.
Después de añadir el bloque Shortcode, sólo tiene que introducir su shortcode en los ajustes del bloque.
El shortcode será proporcionado por varios plugins de WordPress que pueda estar utilizando, como WPForms para formularios de contacto u OptinMonster para marketing por correo electrónico.
Para saber más acerca de cómo utilizar los bloques, consulte nuestro tutorial de Gutenberg.
Ahora puede guardar su entrada o página y obtener una vista previa de los cambios para ver el shortcode en acción.
Añadir un shortcode en los widgets de la barra lateral de WordPress
También puedes utilizar shortcodes en los widgets de la barra lateral de WordPress.
Simplemente visita la página Apariencia ” Widgets y añade un bloque de widget ‘Shortcode’ a una barra lateral.
Ahora, puedes pegar tu shortcode dentro del área de texto del widget.
No olvides hacer clic en el botón “Actualizar” para guardar los ajustes de tu widget.
Después de eso, usted puede visitar su sitio web de WordPress para ver la vista previa en vivo del shortcode en el widget de la barra lateral.
Añadir un shortcode en el antiguo editor clásico de WordPress
Si todavía utilizas el antiguo editor clásico de WordPress, a continuación te explicamos cómo añadir shortcodes a tus entradas y páginas de WordPress.
Simplemente edite la entrada y la página donde desea añadir el shortcode. Puede pegar el shortcode en cualquier lugar dentro del editor de contenido donde desea que se muestre. Sólo asegúrese de que el shortcode está en su propia línea.
No olvides guardar los cambios. Después de eso, puedes obtener una vista previa de tu entrada y página para ver el shortcode en acción.
Añadir un shortcode en los archivos de tema de WordPress
Los shortcodes están pensados para ser usados dentro de entradas, páginas y widgets de WordPress. Sin embargo, a veces, es posible que desee utilizar un shortcode dentro de un archivo de tema de WordPress.
WordPress te lo pone fácil, pero tendrás que editar los archivos de tu tema de WordPress. Si no lo has hecho antes, consulta nuestra guía sobre cómo copiar y pegar código en WordPress.
Básicamente, puede añadir un shortcode a cualquier plantilla de tema de WordPress simplemente añadiendo el siguiente código:
<?php echo do_shortcode('[your_shortcode]'); ?>
Ahora WordPress buscará el shortcode y mostrará su salida en la plantilla de su tema.
Cómo añadir un shortcode en archivos de temas en bloque con el editor de sitio completo
Si está utilizando un tema de bloque, entonces le resultará más fácil añadir shortcodes en los archivos de su tema de WordPress utilizando el editor de sitio completo.
Puede acceder a esta herramienta seleccionando Apariencia ” Editor en el escritorio de WordPress.
Se le mostrará la plantilla de inicio de su tema por defecto, y puede cambiar a otras plantillas seleccionando la opción “Plantillas”.
Una vez que haya elegido una plantilla, puede empezar a editarla al hacer clic en el panel derecho del editor. El editor llenará la pantalla.
Ahora puedes hacer clic en el icono ‘+’ del insertador de bloques y buscar el bloque shortcode. Después de eso, simplemente arrástrelo a la plantilla y escriba el shortcode que desea utilizar.
No olvide hacer clic en el botón “Guardar” de la parte superior de la pantalla para guardar los cambios.
Cómo crear su propio shortcode personalizado en WordPress
Los shortcodes pueden ser realmente útiles cuando se quiere añadir contenido dinámico o código personalizado dentro de las entradas y páginas de WordPress. Sin embargo, si desea crear un shortcode personalizado, entonces se requiere un poco de experiencia de codificación.
Si se siente cómodo escribiendo código PHP, aquí tiene un ejemplo de código que puede utilizar como plantilla:
// function that runs when shortcode is called
function wpb_demo_shortcode() {
// Things that you want to do.
$message = 'Hello world!';
// Output needs to be return
return $message;
}
// register shortcode
add_shortcode('greeting', 'wpb_demo_shortcode');
En este código, primero creamos una función que ejecuta un código y devuelve el resultado. Después de eso, creamos un nuevo shortcode llamado ‘greeting’ y le dijimos a WordPress que ejecutara la función que habíamos creado.
Puede añadir este código al archivo functions. php de su tema manualmente o utilizar un plugin de fragmentos de código como WPCode.
Para más detalles, puede consultar nuestra guía para añadir código personalizado en WordPress sin romper nada.
Una vez hecho esto, puedes añadir este shortcode a tus entradas, páginas y widgets utilizando el siguiente código:
[saludo]
Ejecutará la función creada y mostrará la salida deseada.
Veamos ahora un uso más práctico de un shortcode.
En este ejemplo, mostraremos un banner de Google AdSense dentro de un shortcode:
// The shortcode function
function wpb_demo_shortcode_2() {
// Advertisement code pasted inside a variable
$string .= '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-0123456789101112"
data-ad-slot="9876543210"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
// Ad code returned
return $string;
}
// Register shortcode
add_shortcode('my_ad_code', 'wpb_demo_shortcode_2');
No olvide sustituir el código del anuncio por su propio código de anuncio.
Ahora puede utilizar el shortcode [my_ad_code] dentro de sus entradas, páginas y widgets de la barra lateral de WordPress. WordPress ejecutará automáticamente la función asociada al shortcode y mostrará el código del anuncio.
Shortcodes vs. Bloques Gutenberg
A menudo los usuarios nos preguntan acerca de las diferencias entre shortcodes vs. bloques de Gutenberg.
Básicamente, los bloques le permiten hacer lo mismo que los shortcodes pero de una forma más fácil de usar.
En lugar de requerir que los usuarios añadan un shortcode para mostrar contenido dinámico, los bloques permiten a los usuarios añadir contenido dinámico dentro de entradas/páginas con una interfaz de usuario más intuitiva. Muchos plugins populares de WordPress han pasado a utilizar bloques en lugar de shortcodes porque son más fáciles de usar para los principiantes.
Hemos elaborado una lista de los plugins más útiles del bloque Gutenberg para WordPress que quizás quieras probar.
Si quieres crear tus propios bloques Gutenberg personalizados, puedes seguir nuestro tutorial paso a paso sobre cómo crear bloques Gutenberg personalizados en WordPress.
Esperamos que este artículo te haya ayudado a aprender cómo añadir un shortcode en WordPress. Puede que también quieras ver nuestra guía sobre cómo crear un tema personalizado de WordPress sin escribir ningún código y nuestra selección experta de los mejores plugins de arrastrar y soltar para el editor de páginas de WordPress.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
Andrew Wilson
Hi Guys,
Is it possible with this plugin to create a unique QR Code for users that sign up to your website?
i.e. a person registers on the website, and as part of that process the back-end creates a unique QR Code for that user which if scanned by a third party takes them to their profile on the website?
WPBeginner Comments
You can create QR codes using this guide:
https://www.wpbeginner.com/plugins/how-to-generate-and-add-qr-codes-in-wordpress/
To create it automatically in the way you mentioned may require custom code.
Moinuddin Waheed
This is very helpful for making our own custom short codes.
I have been using short codes for a while and have thought of making my own short codes to use but was not aware about the process.
I have a bit of coding knowledge and can easily make shortcodes through php functions.
Thanks for the guide.
WPBeginner Support
You’re welcome, glad our guide was helpful
Administrador
Jiří Vaněk
Thank you for the detailed instructions. I was able to add the shortcode to Gutenberg but could not use it as a php code. At the same time, it is evidently that simple. A bit smarter again thanks to wpbeginner.
Mohammed
In Example2 How did you define this shortcode ‘my_ad_code’ thought you didn’t define it as a function?
WPBeginner Support
That is added with the code add_shortcode at the bottom of the example
Administrador
Mohammed
❤️❤️
Appreciate for the best Article
Josh
One picture says “greatings” instead of “greetings”
WPBeginner Support
Thank you for pointing that out, it works as a good reminder to make sure you spell your shortcodes correctly
Administrador
Maya
Thanks for sharing such a detailed article keep up the good work!
WPBeginner Support
You’re welcome, glad you found our guide helpful!
Administrador
abuzar
your guidence is very easy to learn. thanks you
WPBeginner Support
You’re welcome!
Administrador
Hugh
Thanks for the great article. Works like a charm. However, although it is explained on the page link provided in the article, it may have been helpful to many readers if you had reiterated that to create shortcodes yourself (‘How to Create Your Own Custom Shortcode’ section of the article), you simply add the example code provided or your own code to the theme’s (or child theme’s) ‘functions.php’ file. Thanks again!
WPBeginner Support
Thank you for that feedback!
Administrador
Hafed benchellali
Thank you for this great article!
WPBeginner Support
You’re welcome!
Administrador
Susan Benfatto
Thank you for your tutorial, it was very useful
WPBeginner Support
Glad it was helpful
Administrador
Rohmah Azim
Hi
Can you tell me how I can add shortcode to my header?
WPBeginner Support
You would need to use the method for the theme files from this article and add it to your theme’s header file.
Administrador
David
-Hi, you know if its possible to add a box fixed for example with a shortcode inside? TNX
WPBeginner Support
That would depend on the plugin you are using for the shortcode.
Administrador
Tihomir
Hi All
in one of my pages I am using this shortcode [product_category category=’jeans’ number=’1000′ per_page=’1000′] . It shows 1000 products of the chosen category jeans. What I can add to this code to make this 1000 products appear same like on product category page or by with a load more button?
Jose Rodriguez
English translation –> but something happens when I add the shortcode and then some text, it turns out that this text is inside the html of the shortcode in the frontend, how can I avoid that?
loganathan
I am creating an own theme, the problem is that theme does no support shortcode. can anyone help me to enable shortcode functionality for my theme.
Ihsan
thanks for sharing such a nice article..
i want to know how we can use php and html both in short code… waiting for good response thanks…
Melissa Lowe
I installed a Mailchimp for WordPress shortcode ..pasted it at the end of the text version of my document/article & no form was created & this is what it said…..MailChimp for WordPress error: There is no form with ID 0, perhaps it was deleted?
Ashkan
What for $atts in that function ?
Helena
Hi,
I have a widget by the homepage sidebar from a multisite installation and want to have 1 widget (only one) from this sidebar working at the subsites.
It is a text widget with a picture, this picture links to an online ebook.
Do you think I can use this to have it done?
Many thanks!
Vinayak Ganiger
The wp form shortcode is not working in pages but it works fine in posts. My website is vinstechs.com. In my website page named Projects is their, in that the shortcode is not working.
What’s the solution for this, please reply with solution.
Meryl
I have a slightly more complex question.
I’m using a theme with a theme options panel.
I want to use a shortcode inside one of those options.
However the output is just the [shortcode] text. Is there specific syntax I can use or does it differ from theme to theme? It’s taking forever to get answers from the theme dev.
Mayank Jain
Perfect beginner explanation!
Vikash Ahlawat
Very helpful post to create our own plugin.
hirak das
Hi i am having a problem with [login_widget] shortcode.when i inserted this code to any page/post on wordpress i only get the text but not the login form…i am using login widget with shortcode plugin…please help…
Armen
This doesn’t work if you’re trying to place another shortcode within the shortcode you’re creating.
Say I had a shortcode like [jpshare] and I wanted to place it along with other stuff into another shortcode function like in this article to add to the posts, how would you do that?
Mike
No mention in the article WHERE to add the shortcode. Back to Google for a better tutorial.
Drew
It clearly stated the code goes into “functions.php”. If you’re not sure how to use the shortcode, it goes anything you add text.
Ihatewordpress
Hello,
As you can tell from my name I’m very frustrated right now with wordpress.
>>This last part is simple, just add the [adsense] shortcode in the HTML or Visual views of the Post or Page content editor.<<
Not even a tiny clue how to do that – would you be willing to expand on this? Thank you
WPBeginner Support
WordPress uses shortcodes to add functionality into posts and pages. Like in this tutorial if you wanted to display advertisement code, then you will create a shortcode for it. Once you have created a shortcode you can use it in your posts and pages. Create a new post or edit an existing one and add your shortcode with square brackets in the post content area, like [adsense].
Administrador
Brock
I installed Popup manager plugin for newsletter subscribers. I got the popup to appear by following your suggestion of putting the shortcode in a comment on my main page. This works but only if a person expands my first comment to read the entire thing. Where/how do I paste the shortcode to get the popup to appear when someone visits my page without requiring them to do anything else? I’m trying to find something in the template customization options but nothing is standing out.
Patty
Please help me understand if this is using a shortcode plugin properly. I need to display the date of the last update to a post or page to stop Google structured errors. I am using default 2014 only with plugins. I found a shortcode plugin named “Last Updated Shortcode” that seems to do what I need. I am wondering if this is what I do.
I would install the plugin, and then activate the plugin. Then on the page/post I would Edit page/post, and at the bottom of the post (or anywhere else if I prefer) add the shortcode. So I would literally type [lastupdated] The last updated date should then appear, correct???
And hopefully, Google will be happy and stop emailing notices of structured errors.
WPBeginner Support
Yes. We are not sure about how it will affect your SEO though. You may want to take a look at how to display the last updated date of your posts in WordPress.
Administrador
Larry Leek
I’m guessing using the short codes for things like countdown timers is is only for wordpress.org or self hosted wp users correct?
WPBeginner Support
Yes.
Administrador
Anibal
Hi I’m having trouble with the short code [tpe mylang lang=’es, en’] I know WP has recently changed this shortcode replacing the old [tp mylang=”yes” lang=”es, en” ] for the new one, but I’ve done the replacement and I still get to a 404 Nothing found error page, whenever I click on a link with this code. Any Ideas?
WPBeginner Support
You are probably using Transposh plugin. Please contact the plugin support, they would be able to help you better.
Administrador
Akshat Verma
can you recommend any good shortcode plugin for wordpress 4.2
Steve
I am having trouble figuring out how to add code comments to a page with just shortcode in it. I’ve tried HTML & PHP comment tags and when added the shortcode doesn’t work anymore. The reason I would like to comment the code is that I would like to document information about the shortcode in the page I call it from ( I may not be the site admin forever).
WPBeginner Support
WordPress will strip out PHP or HTML comments in post editor. If you were using Edit Flow, then you could leave a note below the post. Right now you can switch to Text editor and leave HTML comment, but as soon as some user views the post in visual editor it will be stripped out again.
Administrador
Steve
It strips out the comments AND puts in a blank line for each comment. I put the comments below the shortcode and that works fine.
Thanks for helping me understand what was going on.
Michael
When I add shortcode to posts, whether it be in the middle of an article or at the end, the actual element always appears at the top of the post, any idea why?
Malte
Same here! How to fix that?!
Malte
Okay… Use return instead of echo and everything is k!
James Newman
@MALTE – I have the same issue. Can you clarify which file needs to be edited? I looked at the .php files for the plugin and could not find any echo statements to replace.
Thanks!
WPBeginner Staff
Simply copy [rx_aeolus_three_cols] and paste it in a WordPress page. Save your page and then preview it. However, you will first have to create your portfolio in the plugin. Otherwise you will not see anything, because there is nothing for the plugin to display.
Usha
I have downloaded a plug-in ‘Aeolus portfolio’ for the WordPress 3.9.2 running Twenty Eleven theme. I have been given the following shortcodes in the plug-in setting:
[rx_aeolus_three_cols]-Displays all portfolio as three columns.
[rx_aeolus_two_cols]-Displays all portfolio as two columns.
[rx_aeolus_one_col]-Displays all portfolio as one column.
Can anyone help as to how these short code can be incorporated in a page. I am new to WP plugins and badly need help.
Thanks
Usha
Sweetbreeze Tornado
What if you want to add a button with shortcode?
Dan
Thanks! This thread helped me a lot.
Just in case someone else lands in here and need to use a more complex HTML/PHP code structure inside a shortcode, this is an example using some aditional options from the WordPress Shortcodes API documentation:
Place this (and modify as needed) inside your functions.php:
http://pastie.org/9454401
Then you just use this shortcode inside your WordPress content
[mycustomshortcode]
Greetings!
Rob
You’re the man! This is exactly what I needed. Thank you.
WPBeginner Staff
You can add this code in your theme’s functions.php file.
Aymen Benzarti
HI
I’m beginner and this is my first time with wordpress
so the first question when i tried this tutorial is in which file i have to write this code ?
Nidesh
Hi,
Could you please tell me whether i have to put short codes to a particular page if i want any particular plugin to be displayed in that particular page.
E.g. I’ve installed Collabpress plugin. And i don’t see it’s UI in the front end of my site. So do i have to insert any shortcode to a page for it to be displayed?
WPBeginner Support
Nidesh, yes you will be using shortcodes to do that. Please check out our guide on using Collabpress
Administrador
Christina
I would like to add the subscribe shortcode to my side menu. How do I do this?
Amber T
I am just a little confused… where am I embedding this shortcode.
I have a columns plugin that provided the shortcode with a click of a buton, not sure if I have to take the code and embed it in my html.
please help.
thanks in advance!
WPBeginner Support
just put the shortcode in your post content. Click on the preview button to see how it looks before publishing your post.
Administrador
Carol Manser
Really? Easy? Simple? This website is great but it says it is for beginners. I’ve been using Wordpress for 2 years and yet I did not understand it at all. It’s quite annoying the way geeks always bang on about how easy something is and then write something totally incomprehensible to ordinary humans – just like every Math teacher I ever had.
OK, write an article that can only be understood by geeks – fine, but please don’t keep telling me how easy it is
output? string? content editor – where is it? define a function? I wish you would because I don’t know what it is.
“This function is pretty straightforward – it just returns my Google Adsense code as a string” –
a string of what? etc etc. Just saying….
WPBeginner Support
We totally agree with you that sometimes when writing we may feel that we have explained everything clearly for beginners, but a beginner level user may still not be able to understand it. This is why we have comments and we will be happy to explain it to you more
A shortcode is a short+code. WordPress allows you to generate shortcodes for your programing code blocks called
functions
. Since a user can not write programming code in the Post Editor when writing a new post. The shortcodes provide users a way to add those programming codes into a post without writing the full code in post editor.When WordPress finds a shortcode in a post like this:
[my_shortcode]
It then executes the programming code associated with that particular shortcode.
The example given in the article above, creates a function get_adsense. When this function is executed it outputs the adsense code. We hope this explains it for you. Let us know if you have any more questions.
Administrador
Stacy
Or the instructions are 3 lines and your wondering where are the rest of the instructions????
Przemek
Totally, agree. I struggled to understand most of it, too.
Alan Murray
Can I use a shortcode on a Standalone HTML page to link to a page on my blog?
If so how do I embed it? Does the file need to be a PHP file?
I can’t seem to find anywhere on the net providing information on using sortcode outside Wordpress pages or posts.
WPBeginner Support
Alan, shortcodes are a WordPress feature the page should be a WordPress page in order to execute the shortcode.
Administrador
DavidA
Do you know, how to add a shortcode on a website from an other website WordPress? (multisite)
Thx
WPBeginner Support
yes by creating a network wide plugin all blogs on the multisite can share the shortcode.
Administrador
Lucy
Very good one!
John Rose
Clear and concise. Thank you so much. – John
Luke Ward
Hello, thank you for this, it’s helped a lot.
However I would like to know how to add more than one adsense in as a shortcode.
eg [adsense1] – displays one advert [adsense2] displays a different advert.
Thanks!
Editorial Staff
Follow the same process. Change the word adsense with adsense1.
Administrador
Luke Ward
Thank you, sorry for the noob question!
Also I have another problem now, I’m using this code to add adsense which works with responsive designs using javascript. You can see the code I’m using in the link below…
http://www.labnol.org/?p=25252
When this is added in after reuturn’ – nothing is displayed.
Hope you can help with this problem as I cannot seem to find out how anywhere.
Thanks
Editorial Staff
The issue is with the syntax.
Paul
Just came across this as I’m looking to add my own shortcodes, I can understand the function part of it, but which document do you include the “hook up”
“add_shortcode(‘adsense’, ‘get_adsense’); line”
that would be helpful to me
Thanks
Editorial Staff
You add that right after the function part.
Administrador
Patrick
I’m clueless and am trying to create a short code to insert the blog’s owner’s user name. Any ideas?
Editorial Staff
Write a function that outputs the username. Then put that function in the shortcode output. Unfortunately, we do not write custom codes like those on requests.
Administrador