Cuarto Geek
  • Inicio
  • Comprar por internet
  • Toys
  • WordPress

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

By eK • 1 octubre, 2011 • Tutoriales, Wordpress
code wordpress

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

<script type="text/javascript" src="http://direcciondemisitio.com/adsense.js"></script>

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.

<script type="text/javascript">adsenseTop();</script>

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

<script type="text/javascript">adsenseSidebar();</script>



Hacks y Tips
Tweet
0
Transferir un dominio de Namecheap a Name
¿Cómo solicitar el aumento de velocidad en Telmex?

Te puede interesar...

  • Alternativa Really Simple SSL

    Alternativa Really Simple SSL

  • redimir coppia digital pelicula estados unidos mexico 2

    Canjear la copia digital de una película de USA en México

  • devolucion mercadolibre

    MercadoLibre: que hacer cuando rechazan un paquete enviado por MercadoEnvíos

  • retirar dinero mercadopago

    Retirar dinero en MercadoPago

No hay comentarios

    Publicar comentario Cacelar respuesta

    Subscribe & Follow

    Entradas Populares

    liverpool destacados cg

    Experiencia al comprar en la página online de Liverpool

    On 8 marzo, 2012
    01
    linio destacados

    Experiencia al comprar en la página de Linio (México)

    On 7 enero, 2013
    02
    amazon destacados cg

    Comprar en Amazon desde México

    On 24 diciembre, 2012
    03

    Entradas Recientes

    • hbomaxlat

      El timo de hbomaxlat.com

      5 abril, 2021
    • Alternativa Really Simple SSL

      Alternativa Really Simple SSL

      27 noviembre, 2020
    • starzplay oferta tiempo limitado

      STARZPLAY – promoción por tiempo limitado

      18 septiembre, 2020
    • curiosidades pelicula fantasia disney min

      Curiosidades de la película Fantasía

      19 febrero, 2020
    • curiosidades pelicula el jorobado de notre dame

      Curiosidades de la película El Jorobado de Notre Dame

      15 enero, 2020

    Made with in Seattle

    TVLOGIA