¿Quieres insertar anuncios dentro del contenido de tus entradas en WordPress?
El contenido de sus entradas es el lugar en el que los visitantes tienen una mayor participación en su sitio web, lo que lo convierte en el lugar perfecto para mostrar un anuncio.
En este artículo, mostraremos tres formas de insertar anuncios dentro del contenido de sus entradas en WordPress.
¿Por qué insertar anuncios en el contenido de sus entradas en WordPress?
Los banners y los anuncios en la barra lateral son una buena forma de ganar dinero en los blogs de WordPress. Sin embargo, también son fáciles de ignorar para los visitantes.
La gente visita su sitio para leer su contenido, y puede que no preste tanta atención a su barra lateral o a otras zonas de la página. Como el contenido de la entrada es lo que más atrae la atención de los visitantes, es el lugar perfecto para mostrar anuncios.
Dicho esto, veamos tres formas diferentes de insertar anuncios dentro del contenido de sus entradas en WordPress.
Si prefiere ir directamente a un método concreto, puede utilizar los siguientes enlaces.
Método 1. Insertar anuncios dentro del contenido de la entrada usando WPCode (Automáticamente)
Una forma de insertar anuncios dentro del contenido de tus entradas es utilizando el plugin gratuito WPCode.
WPCode es uno de los mejores plugins de fragmentos de código de WordPress del mercado y también uno de los mejores plugins de gestión de anuncios de WordPress. Le permite insertar fácilmente código para colocar anuncios en cualquier página, entradas o área de widget de su sitio web de WordPress.
Puede mostrar anuncios de redes publicitarias de terceros, como Google AdSense. O bien, puede mostrar sus propios anuncios alojados, lo cual es perfecto para vender anuncios en su blog de WordPress.
Para empezar, necesitarás instalar y activar el plugin WPCode. Si necesitas ayuda, consulta nuestra guía sobre cómo instalar un plugin de WordPress.
Una vez activado, vaya a Fragmentos de código ” + Añadir fragmento desde su escritorio de WordPress.
Esto le llevará a la biblioteca integrada de fragmentos de código. Pase el cursor por encima de la opción “Añadir su código personalizado (nuevo fragmento)” y haga clic en el botón “Usar fragmento” para seleccionarlo.
A continuación, deberá añadir un título a su anuncio escribiendo en el campo “Añadir título para fragmento de código”.
Los visitantes de tu sitio no verán el título ya que es solo para tu referencia.
A continuación, debe elegir el tipo de anuncio que desea colocar en su sitio.
Una opción es utilizar el código de anuncio proporcionado por un programa como Google AdSense.
Si está utilizando el código de Google AdSense, entonces es posible que desee ver nuestra guía sobre los tamaños y formatos de banner de Google AdSense de mayor rendimiento. También tenemos una guía completa sobre cómo optimizar sus ingresos de AdSense en WordPress.
Otra opción es crear su propio anuncio. En ese caso, tendría que obtener el código de la persona que le paga por mostrar el anuncio en su sitio de WordPress o escribir el código usted mismo.
Una vez que tenga el código del anuncio, simplemente cópielo y péguelo en la casilla “Vista previa del código”.
También debe seleccionar “Fragmento de código HTML” como “Tipo de código” en la lista desplegable de la parte derecha de la pantalla.
A continuación, desplácese hasta la sección “Inserción”. Puede elegir entre dos opciones principales de inserción:
- Auto-Insertar – El código del anuncio se insertará automáticamente y se ejecutará en su sitio web en la ubicación que usted elija.
- Shortcode – El código del anuncio no se insertará automáticamente. Obtendrá un shortcode que podrá insertar manualmente en cualquier lugar de su blog WordPress.
Haga clic en el método “Auto-Insertar” para mostrar automáticamente anuncios dentro del contenido de las entradas.
A continuación, elija la opción “Insertar después del párrafo” de la lista desplegable situada junto al campo “Ubicación”.
También puede modificar el “Número de inserción” para elegir el número de párrafos tras los que insertar el fragmento de código. Por ejemplo, si desea mostrar el anuncio después del segundo párrafo en lugar del primero, simplemente sustituya el 1 por un 2.
Además de insertar anuncios después de un párrafo, también puede mostrar anuncios automáticamente en ubicaciones (funciones de WordPress) como antes o después del contenido, entre entradas, antes o después de extractos, etc.
Con la versión premium de WPCode, también puedes insertar anuncios en ubicaciones de WooCommerce como antes o después de los productos, carrito y página de finalizar compra / pago, por nombrar algunos.
WPCode Pro también te permite programar los fragmentos de código de tus anuncios con una fecha de inicio y fin. Esto es perfecto para mostrar anuncios en la temporada de vacaciones o para otras promociones de tiempo limitado.
A continuación, desplácese hasta la sección “Tipo de dispositivo”. Aquí puede elegir si desea mostrar su anuncio en cualquier tipo de dispositivo, solo en ordenadores de sobremesa o solo en móviles.
Si desea limitar las páginas o entradas en las que se inserta automáticamente el fragmento de código del anuncio, puede desplazarse hasta la sección “Lógica condicional inteligente”.
Por ejemplo, puede ocultar sus anuncios en determinados tipos de página o URL de página.
Para ayudarte a organizar tus anuncios, puedes ir a la sección “Información básica”. En esta área, puede añadir etiquetas y notas que le ayuden a recordar para qué sirve el fragmento de código de su anuncio.
También hay un campo “Prioridad” que le permite controlar el orden en que se ejecutan los fragmentos de código cuando desea mostrar varios fragmentos en el mismo lugar.
Todos los fragmentos de código tienen una prioridad de 10 por defecto, por lo que si desea que el código de su anuncio se muestre antes que los demás, sólo tiene que establecer la prioridad en un número inferior.
Una vez que hayas terminado de trabajar en tu anuncio, es hora de publicarlo.
Para ello, vuelva a la parte superior de la página y active el conmutador de “Inactivo” a “Activo”. A continuación, haz clic en el botón “Guardar fragmento de código”.
Ya está. Su anuncio se insertará automáticamente en el contenido de su entrada si ha seleccionado el método “Auto-Insertar” que se muestra en este tutorial.
Si elige el método de inserción ‘Shortcode’, puede crear una nueva página o entrada, o abrir una para editarla. A continuación, sólo tiene que encontrar el lugar exacto donde desea mostrar este anuncio dentro de su contenido de la entrada, y crear un nuevo bloque shortcode.
A continuación, puede seguir adelante y pegar el shortcode en este bloque. Para obtener instrucciones paso a paso, consulte nuestra guía para principiantes sobre cómo añadir un shortcode en WordPress.
Ahora, puede visitar la página o entrada para ver el anuncio dentro del contenido de su entrada.
Nota: Si muestra anuncios de Google AdSense, el anuncio puede tardar entre 20 y 30 minutos en aparecer en la página.
Método 2. Insertar anuncios en el contenido de una entrada utilizando Ad Inserter
Otra opción es utilizar Ad Inserter. Se trata de un plugin de gestión de anuncios para WordPress que puede mostrar tanto anuncios alojados como anuncios proporcionados por una red.
Si utiliza una red, sólo tiene que pegar el código de su anuncio en el plugin Ad Inserter. Sin embargo, si está creando un anuncio alojado, tendrá que escribir el código usted mismo u obtenerlo de la persona que paga por mostrar su anuncio en su sitio web.
Lo primero que debe hacer es instalar y activar el plugin gratuito Ad Inserter. Si necesita ayuda, consulte nuestra guía sobre cómo instalar un plugin de WordPress.
Una vez activado, vaya a Ajustes ” Ad Inserter.
En esta pantalla, cada pestaña es un anuncio diferente. Esto le permite crear varios anuncios diferentes y colocarlos en su sitio web.
Ahora puede escribir o copiar/pegar el código del anuncio que desea mostrar en el contenido de su entrada.
El siguiente paso es colocar este anuncio en su sitio web. Una opción es añadir el anuncio a cualquier página, entrada o área preparada para widgets mediante un shortcode.
Otra opción es decirle a Ad Inserter que añada automáticamente este anuncio a cada entrada, en un lugar determinado como, por ejemplo, después de cada tercer párrafo.
Si quieres añadir este anuncio a tus entradas automáticamente, empieza por marcar la casilla “Entradas”.
A continuación, tendrá que abrir el menú desplegable “Inserción” y elegir dónde debe mostrar este anuncio Ad Inserter.
Como queremos insertar anuncios dentro del contenido de la entrada, normalmente querrá elegir Antes del párrafo, Después del párrafo, Antes de la imagen o Después de la imagen.
Después de elegir una opción de la lista, escriba exactamente dónde debe aparecer este anuncio.
Por ejemplo, si quisiera mostrar el anuncio después del segundo párrafo, entonces escribiría ‘2’ como puede ver en la siguiente imagen.
Cuando estés satisfecho con los ajustes, haz clic en el botón “Guardar ajustes”.
Ad Inserter insertará este anuncio en el contenido de su entrada, en el lugar que elija.
Al igual que hemos mencionado anteriormente, también puede colocar este anuncio en su sitio utilizando un shortcode.
Para ello, haga clic en el botón “Manual” y, a continuación, marque la casilla “Shortcode”.
Una vez hecho esto, copie el shortcode del Ad Inserter. A continuación, puede hacer clic en el botón “Guardar ajustes” para guardar su anuncio.
Una vez hecho esto, ya puedes colocar este shortcode en cualquier página, entrada o área preparada para widgets. Para instrucciones paso a paso, puedes ver nuestra guía sobre cómo añadir un shortcode en WordPress.
Método 3. Insertar anuncios dentro del contenido de entradas usando código (Avanzado)
También puedes añadir un anuncio al contenido de tus entradas en WordPress mediante código.
Dado que está editando el código de su sitio, este no es el método más fácil para los principiantes. Sin embargo, le permite crear anuncios sin tener que instalar un plugin especial de gestión de anuncios.
Para insertar un anuncio utilizando código, abra el archivo functions.php de su tema, cree un plugin específico para el sitio o utilice un plugin de fragmentos de código.
De nuevo, recomendamos usar el plugin gratuito WPCode porque facilita la tarea de pegar fragmentos de código en WordPress, sin necesidad de editar el archivo functions.php de tu tema.
Además, WPCode viene con validación inteligente de fragmentos de código para ayudarte a prevenir errores comunes de código y protegerte de romper tu sitio.
A continuación, puede añadir el siguiente código:
//Insert ads after second paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>Ads code goes here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
Este código mostrará un anuncio después del segundo párrafo del contenido de una entrada.
Si desea mostrar su anuncio en otra ubicación, sólo tiene que cambiar la siguiente sección:
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 3, $content );
}
En el código de ejemplo anterior, puede ver que estamos insertando el anuncio después del tercer párrafo.
Una vez hecho esto, puede seguir adelante y escribir o pegar el código de su anuncio. Éste es el código que controla el aspecto y el funcionamiento de tu anuncio.
Añadirás este código como el valor $ad_code, que es donde dice ‘Añadir código va aquí’.
$ad_code = '<div>Ads code goes here</div>';
Una vez hecho esto, ya puedes publicar tu anuncio. Para ello, active el plugin específico de su sitio, guarde los cambios realizados en el archivo functions.php de su sitio o active y guarde su fragmento de código en WPCode.
Ahora, si visita su sitio web, debería ver su anuncio en directo.
Esperamos que este artículo te haya ayudado a aprender cómo insertar anuncios dentro del contenido de tus entradas en WordPress. Puede que también quieras aprender cómo aumentar el tráfico de tu blog, o comprobar nuestra lista de las mejores herramientas de WordPress y plugins SEO que deberías usar.
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.
Syed Balkhi says
Hey WPBeginner readers,
Did you know you can win exciting prizes by commenting on WPBeginner?
Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
You can get more details about the contest from here.
Start sharing your thoughts below to stand a chance to win!
Astha says
Hey,
What is the meaning of “Permissions for ads access” in your new 1.1.1 update in this plugin?
Please explaim.
Thank you.
reles says
ty
if I want two banners?
Paragraph 2 and paragraph 5?
phil says
Just copy the function and rename one for have a different function, then choose another paragraph … easy
Fika Thiana says
Thank you so much, I have my adsense shows in the middle of the post. I’ve tried some other tutorial but this tutorial really work like a charm.
Waleed Barakat says
Wow! Amazing solution! working like a charm. Thank you
Micheal says
Please which plugin can i use to add “Read Also(another post)” within my post content to link to other post within my website for users to read another post.
WPBeginner Support says
Hi Michael,
You don’t need a plugin for that. You can link to the posts in post editor. You can also use a related posts plugin which will show similar articles from your website at the end of each post.
Administrador
Ed says
Working. Just removed <?php
and paste at the bottom.
Abhijit Badgujar says
Hi,
I installed your plugin and did every step you instructed. But I can’t see the ads in my post.
Abhijit Badgujar says
Hi, Ij changed the setting and it worked. Thanks for the plugin.
Taylor says
Hi. Great thanks for the code. However, is it possible to increase the space a little before and after the ad, like increasing the margin slightly or something like that. Thanks
Taylor
Aamir says
what should i do if i want to put ads on videos…
i have movie site and i want to put ads on movies videos..
please help….
Vitor Hugo says
Nice tip, I was looking for it… but for some reason, the code (the plugin I don’t know, didn’t use it, only the code) insert a random orphan closure paragraph tag () in the end of the post.
Sam says
When using manual code via functions.php, how do you get the text to wrap around the ad code?
sandeep kumar says
I have tried you plugin INSERT ADS and completely satisfied as it doesn’t require any coding skills
Bejek says
how add random post in the_content after 2 paragraf
Deise de Oliveira says
Thanks! Tha’s exactly what I was looking for!
Robert says
How do you place the ads in the center?
Sam says
add before ad code and end with
James Burnette says
I have a post adverts google ad above the content and it causes the adsense code to be shown when shared on fb. Any suggestions?
Byron says
Hi,
I want to have a [show more] after the second paragraph and a [/show more] after the last paragraph of all posts, to show only on mobile devices.
I’ve tried ad inserter but the close [/show more] doesnt quite work. Is there anything you could recommend for me to get this working?
Thanks
Syed Irfan says
What to do if i want to add more Ads?
Arta says
How can I have a Facebook box slide up at the end of the content?
Just like list25.com
When you finish reading and you reach the end of the content, facebook box slides up
WPBeginner Support says
List25 uses custom code for that. May be we will add a tutorial about it in the future. Meanwhile, did you check OptinMonster‘s slide in optin? It is a lot easier.
Administrador
Arta says
Thank you
it worked well.
Umer Shah says
Hi,
I am using a insert post ad plugin on my blog, its working fine except the position of the ad which is left. How can I move it to center?
Alex Sume says
Hello,
I use this code and it works well on my blog. Now i want to add more 1 extra ads code to display after another paragraph.
Please help.
Vincent says
The plugin method is great and I’ve added a couple of ads; one appears after 3rd paragraph and the other appears at the end of the content. This is exactly what I’m looking for since editing the code is always a pain for me every time my site’s theme gets updated. I know I should be using a child theme, but that’s just a lot of mess — your method is much cleaner and less headache. Thanks.
WPBeginner Support says
Glad you found it helpful
Administrador
Salman Naqvi says
Hey , I also Implemented this code and it worked well ! Now i want to add code to show add at the end of the content ? How Would I Change this php code to show add at the end ?
Regards
Josh says
Is there a way to set which ads will show for various post categories? For instance, I might show a different CTA for a technology post than I would for finance post.
Possible?
Muhammad muneeb says
I want to add ads in the side of post content please help me for this.
shane says
Not happy now. Added the code and now my site is broken. What have I done wrong. I cant even load my site anymore?
I added the code to the bottom line as is explained in here. then removed the “ads code goes here” and replaced with my adsense code. But now my site wont even load. HELP please.
PLEASE
Arun Kallarackal says
Hi Syed,
The site specific plugin method you provided is working like a charm for me. Thanks!
Is there any way to trigger the site specific plugin only if a blog post has a minimum number of paragraphs?
For example- I want the ad to appear only if the blog post is at least 10 paragraphs long. Is there any way to add that criteria to the site specific code you provided? The ad should appear only if the minimum para criteria has been satisfied.
Any help would be appreciated!
Arun
pawan says
Not working at all.. I help try all the steps but it doesn’t work. Any help.!!
Antonia says
My functions.php file is full of stuff. Where exactly do I paste the code? Thank you!
WPBeginner Support says
At the end of the file. If you have a
?>
tag at the end, then paste the code before it.Administrador
Srijan Singh says
Hey, I added above codes to my functions.php file but then I got these errors:
Warning: session_start(): Cannot send session cache limiter – headers already sent (output started at /home1/srijan1998/public_html/football2mania.com/wp-content/themes/gameday/functions.php:1320) in /home1/srijan1998/public_html/football2mania.com/wp-content/plugins/accesspress-social-counter/accesspress-social-counter.php on line 139
Warning: Cannot modify header information – headers already sent by (output started at /home1/srijan1998/public_html/football2mania.com/wp-content/themes/gameday/functions.php:1320) in /home1/srijan1998/public_html/football2mania.com/wp-includes/pluggable.php on line 1228
so I decided to logout my dashboard, i tried to login back by going to my w-admin page, these are errors showed up on blank screen.
I’m just not able to login, could you help please?
WPBeginner Support says
Please see our guide on what to do when you are locked out of WordPress admin area. Remove the code from the functions file.
Administrador
Solomon says
Please where do I implement this code in the functions.php file. You didn’t mention to insert the code after a specific line. Thanks
Donovan says
Thanks for the plugin. However, when I deselect the posts and pages options in the settings section it will not save that setting.
Either posts or pages or both have to be checked for the settings to be saved.
Is there a way around this?
Denis says
Hi,
Plugin works fine but how can i center the div class?
display: block margin left right auto; text-align: center….nothing works :/
Thx
Raymond says
Cool! Thanks for the great tip. I manage to add my banner in every page and post.
Cheers!
Husnain Naz says
Can you please tell me how can i display the ad before 1st paragraph. I am using div float right and would like to display the ad beside first paragraph
Indy says
Hi,
Great code snippet. How can you use it to add more than one advert? I need to add two adverts inside the post. This works great for the first one after paragraph 10 but when I tried adding:
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code2, 16, $content );
}
where $ad_code2 is the second adsense code, it shows nothing?
Any help on this will be highly appreciated
Thanks
Indy
toxicchili says
Don’t return the content before you have added both ads.
if ( is_single() && ! is_admin() ) {
$content = prefix_insert_after_paragraph( $ad_code1, 10, $content );
$content = prefix_insert_after_paragraph( $ad_code2, 16, $content );
return $content;
}
I implemented a loop add the code in for each adverts before returning the content.
In my example I am actually storing my adverts in a database then based on the targeting criteria I return an object with all the adverts for the specific ad unit placement. It them loops and add each advert. I have used various different classes in my plugin, so you will need to change the function name to suit yours.
if ( is_single() && ! is_admin() ) {
$adverts = $this->get_ads_query(3);
foreach($adverts as $advert){
$content = $this->insert_into_content( stripslashes_deep($advert->code), 2, $content );
}
return $content;
}
Anubhav says
Hi Indy
You can use the other filter
Given code this
add_filter( ‘the_content’, ‘prefix_insert_post_adsNew’ );
function prefix_insert_post_adsNew( $content ) {
$ad_code = ‘Ads code goes here’;
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 10, $content );
}
return $content;
}
This should work . Do not remove the previous filter just add this below the existing filter
Markart says
You are great! thanks for second ads filter. but some posts have not enough paragraph count.
It does not have the total count of paragraphs. I want to add to the end of the post in the second filter.
How do I do it? sorry for my english thanks!
Kabo says
I’m afraid the code isn’t working anymore.. any tips?
Does it need to be under Single.PHP for some themes maybe?
Evelina says
The plugin does not work on my blog
Mr B says
Thank you for this code. Wow, it did exactly what I needed.
elena says
Hi I just downloaded the plugin and it is exactly what I needed.
However I have a question which I hope you can answer.
I have a lot of articles where my ads don’t apply to. Is there a way to just add the ad when I need it?
I know you have the option to include o or exclude from the current and future posts but what about the old posts? Do I have to do this manually?
arpan says
Hey , will the code method conflict with the auto social media post?
Raquel Smith says
Hello! I am looking to add a custom Pin It button after every first image in my posts. It seems like this method might work. How do I have it show up after the first image, not the first tag? Thanks!
habeeb says
wow! I loveth this. Thanks for the brainwave. But can I install the plugin to add ads, and at the same time I used the code method as well?
Urgent reply Pls…
WPBeginner Support says
Yes you can do that.
Administrador
Ivan says
Yes you can do that but why? Keep in mind that your site safety is comprimitted by using plugins for every little thing you want. This code works and there is no need for extra plugin.
Joseph says
Can you please support for floating left or right ads in single post?
Wayne Elliott says
Plus one. Great plugin. The ability to right align and wrap content around next paragraph (float: right?) would be great. I fiddled around with WP custom css for #boxmap but could not get it right. Any tips.
malik says
How can i make the ads align to the center of the post.
Mohammed says
You can do either style the div element or add Your Ad code here tag to align the ads in center of the post.
Hope it helps.
george says
I’ve installed the plugin and choose the setting ‘post’ but the Addoesn’t show anywhere within the post. I’ve also added the code above to the functions.php file but it didn’t work either and was just a blank page. Can you please help
mahesh says
when i put the code in functions.php its comming database error
Xiao says
You have to remove the <?php tag and paste the rest of the code in functions.php file.
Nate says
How would this function work if you wanted to add two ads. Say one after the 2nd paragraph and then another one after the 4th paragraph?
Michael says
Yes it would be good to know how to do this? I would also like to add in another advert in paragraph 4 for example but duplicating the code results in an error
Favour Ikandu says
Please I’m new to blogging and ads, not to talk of the codes. I want to know if its possible to to add the AdSense code in posts using a smartphone.
Nabeel says
Hi, wanted to know that why do you have above the fold ad on your site?
Please elaborate, as I read it’s bad for seo?
WPBeginner Support says
We do not have any ads above the fold. We have a banner which expands and shows links to different sections of our website. We also don’t think that above the fold ads are bad for SEO unless they are disruptive. Particularly on mobile devices, ads placed just before the content make it difficult for users to tap on links.
Administrador