• Saltar a la navegación principal
  • Saltar al contenido principal
  • Saltar a la barra lateral primaria
logo cuarto geek

Cuarto Geek

Compras por Internet, Tutoriales, Tecnología, Gadgets, Dominios, TV

  • Inicio
  • Comprar por internet
  • WordPress
  • Toys

WordPress: Mostrar publicidad solo a los visitantes que llegan a través de buscadores

octubre 1, 2011 by eK Deja un comentario

Código para mostrar la publicidad solo a quienes llegan a través de un buscador y/o bien desde un enlace en twitter, facebook… el código funciona inclusive si tienes algún sistema de cache, porque yo había utilizado otros códigos que al final nunca funcionaban al tener instalado ya sea WP Super Cache, W3 Total Cache, etc.

Primero hay que crear un archivo js que tenga el siguiente código

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

var ref = document.referrer;
var sevisitor;
var SE = new Array('web.info.com', 'search.', '.yahoo.','/url','/search','.google.','.ask.','.baidu.','.bing.','.aol.','.answers.');
//document.write('<!--'+ref+'-->');
for ( var source in SE){
  var match = ref.indexOf(SE[source]);
  if (match !=-1) {
    Set_Cookie("sevisitor", 1, "", "/", "","");
    sevisitor=true;
  }
}

También debe de contener el código de adsense, el siguiente es suponiendo se trate de un anuncio 336×280, ojo hay que agregar el ad cliente y ad_slot.

function adsenseTop(){
  if (Get_Cookie('sevisitor') || sevisitor){
    var large = '<script type="text/javascript"><!-- \n\
      google_ad_client = "pub-xxxxx"; \n\
    /* xxxxx xxxxx top 336x280, creado 18/08/11 */ \n\
    google_ad_slot = "xxx"; \n\
    google_ad_width = 336; \n\
    google_ad_height = 280; \n\
    --> \n\
</script> \n\
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> \n\
</script> \n\
';
    document.write(large);
  }
}

Al final quedaría de la siguiente manera, es un ejemplo utilizando dos anuncios uno de 336×280 y el otro de 300×250.

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

var ref = document.referrer;
var sevisitor;
var SE = new Array('web.info.com', 'search.', '.yahoo.','/url','/search','.google.','.ask.','.baidu.','.bing.','.aol.','.answers.');
//document.write('<!--'+ref+'-->');
for ( var source in SE){
  var match = ref.indexOf(SE[source]);
  if (match !=-1) {
    Set_Cookie("sevisitor", 1, "", "/", "","");
    sevisitor=true;
  }
}

function adsenseTop(){
  if (Get_Cookie('sevisitor') || sevisitor){
    var large = '<script type="text/javascript"><!-- \n\
      google_ad_client = "pub-xxxxxx"; \n\
    /* xxxx xxxxx top 336x280, creado 18/08/11 */ \n\
    google_ad_slot = "xx"; \n\
    google_ad_width = 336; \n\
    google_ad_height = 280; \n\
    --> \n\
</script> \n\
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> \n\
</script> \n\
';
    document.write(large);
  }
}

function adsenseSidebar(){
  if (Get_Cookie('sevisitor') || sevisitor){
    var large ='<script type="text/javascript"><!-- \n\
google_ad_client = "pub-xxxxxx"; \n\
/* xxxxx xxxxxx sidebar 300x250, creado 18/08/11 */ \n\
google_ad_slot = "xxx"; \n\
google_ad_width = 300; \n\
google_ad_height = 250; \n\
  --> \n\
</script> \n\
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> \n\
</script> \n\
';
    document.write(large);
  }
}

Si también quieres mostrar publicidad a quienes lleguen a través de un click en facebook y/o en twitter entonces hay que añadir:

  • t.co
  • facebook.com/l.php?

Otra cosa que puedes editar es el tiempo de expiración de la cookie, si quieres que la cookie se elimine al cerrar el navegador entonces debes de poner 0.

en lugar de expires = expires * 1000 * 60 * 60 * 24; se pone expires = expires * 0;

Para implementarlo en el theme de wordpress, como digo hay que crear un archivo js, por ejemplo adsense.js el cual debes de subir a tu sitio y posteriormente hacer el llamado ya sea en la plantilla header.php o bien en footer.php por ejemplo

&lt;script type="text/javascript" src="http://direcciondemisitio.com/adsense.js"&gt;&lt;/script&gt;

Luego para colocar la publicidad, en mi caso el código 336×280 se llama adsenseTop y lo utilizo para la plantilla single, entonces en el theme de wordpress en la plantilla single.php hay que editar y añadir el siguiente código en la parte donde se desea mostrar el anuncio.

&lt;script type="text/javascript"&gt;adsenseTop();&lt;/script&gt;

El código de 300×250 llamado adsenseSidebar lo uso en el sidebar, entonces en sidebar.php hay que agregar

&lt;script type="text/javascript"&gt;adsenseSidebar();&lt;/script&gt;

Comparte esta entrada:

Share on X (Twitter) Share on Facebook Share on Pinterest Share on Email

Archivado bajo: Tutoriales, Wordpress Etiquetado con: Hacks y Tips

Interacciones del lector

Deja un comentario Cancelar respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Barra lateral primaria

Buscador

Destacados

cartoon network crossovers

Recuerda los mayores crossovers de la historia de Cartoon Network

cartoon network series producidas por mujeres

Steven Universe, Hora de Aventura: 5 títulos de Cartoon Network con mujeres en producción

scooby-doo multiverso animacion datos

El multiverso de la animación: cinco veces que la pandilla Scooby-Doo ayudó a otros personajes del mundo de los dibujos animados

avengers 60 aniversario vengadores

Vengadores: Los héroes más poderosos de la Tierra cumplen 60 años; descubre más sobre los Avengers

Entradas recientes

  • Relanzamiento Disney+ en América Latina – Estrenos y novedades
  • ¿Cómo cancelar el servicio MVS Hub?
  • Prime Video estrenos 2024
  • Lifetime estrenos 2024
  • Star+ estrenos 2024
  • Disney+ estrenos 2024
  • Estrenos HBO Max 2024

— Privacidad · TVLOGIA · CUARTO GEEK