jueves, 11 de octubre de 2012

añadir un campo en el editor de posts de wordpress

Por ejemplo, si se quiere agregar un "subtítulo", se mete lo siguiente en el functions.php (también se puede meter en un archivo y subirlo a la carpeta plugins):



add_action('admin_menu', 'agregar_campos');
function agregar_campos() {
        add_meta_box('subtitulo','Subtítulo','fn_subtitulo','post','normal','high');
}

function fn_subtitulo() {
        global $wpdb, $post;
        $value  = (get_post_meta($post->ID, subtitulo, true));
        echo '<label class="hidden" for="subtitulo">Subtítulo</label>
        <input type="text" name="subtitulo" id="subtitulo" value="'.htmlspecialchars($value).'" style="width: 600px;" />';
}

add_action('save_post', 'guardar_campos');
add_action('publish_post', 'guardar_campos');
function guardar_campos() {
   global $wpdb, $post;
        if (!$post_id) $post_id = $_POST['post_ID'];
        if (!$post_id) return $post;
        $subtitulo= $_POST['subtitulo'];
        update_post_meta($post_id, 'subtitulo', $subtitulo);
}

add_action('delete_post', 'borrar_campos');
function borrar_campos() {
   global $wpdb, $post;
        if (!$post_id) $post_id = $_POST['post_ID'];
        if (!$post_id) return $post;
        delete_post_meta($post_id, 'subtitulo');
}


y después se llama al campo dentro del loop:

<?php echo get_post_meta($post->ID, subtitulo, true); ?>

lunes, 8 de octubre de 2012

twitter button en el loop de wordpress

el siguiente es el código:


<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
   <a href="http://twitter.com/share" class="twitter-share-button"
      data-url="<?php the_permalink(); ?>"
      data-via="USUARIO DE TWITTER SIN @"
      data-text="<?php the_title(); ?>"
      data-related="brp"
      data-count="vertical">Tweet</a>



donde:
data-url – This fetches the URL that you want to share (You do not need to change this).
data-via – This tells twitter who was the original tweeter by adding via @wpbeginner (Make sure you change it to your twitter account).
data-text – This fetches the title of your post (You do not need to change this).
data-related – This adds recommended users to follow. You are allowed up to two Twitter accounts for users to follow after they share content from your website. These accounts could include your own, or that of a contributor or a partner. The first account is the one that is shared in data-via property. (Make sure you change it to one of your other twitter accounts, or remove it). If you don’t, then you will be recommending @syedbalkhi (Founder of WPBeginner). The correct format to enter data in this variable is twitterusername:Description of the User
data-count – This tells twitter’s script which style of button you want to show. You have three option (vertical, horizontal, none). data-lang – This variable tells twitter which language it should be in. Default value is ‘en’ for English, and we have left it at that.

jueves, 27 de septiembre de 2012

Sumar valor a variable con jQuery

Para que no se me olvide la sintaxis:


        <script type="text/javascript">
$(document).ready(function(){
var $alturaSidebar = $("#sidebar").height()-20;
$("#content").css("min-height", $alturaSidebar );
});
</script>

lunes, 24 de septiembre de 2012

Borrar valor por defecto de un input con jquery


<script type="text/javascript">
  $(document).ready(function(){
   $('input').each(function(){
     // tomamos el valor actual del input
     var currentValue = $(this).val();
     // en el focus() comparamos si es el mismo por defecto, y si es asi lo vaciamos
     $(this).focus(function(){
     if( $(this).val() == currentValue ) {
     $(this).val('');
     };
     });
     // en el blur, si el usuario dejo el value vacio, lo volvemos a restablecer
     $(this).blur(function(){
     if( $(this).val() == '' ) {
     $(this).val(currentValue);
     };
     });
  });
 });
 </script>

miércoles, 5 de septiembre de 2012

Códigos para poner the_time en wordpress

Day of Month
dNumeric, with leading zeros01–31
jNumeric, without leading zeros1–31
SThe English suffix for the day of the monthst, nd or th in the 1st, 2nd or 15th.
Weekday
lFull name  (lowercase 'L')Sunday – Saturday
DThree letter nameMon – Sun
Month
mNumeric, with leading zeros01–12
nNumeric, without leading zeros1–12
FTextual fullJanuary – December
MTextual three lettersJan - Dec
Year
YNumeric, 4 digitsEg., 1999, 2003
yNumeric, 2 digitsEg., 99, 03
Time
aLowercaseam, pm
AUppercaseAM, PM
gHour, 12-hour, without leading zeros1–12
hHour, 12-hour, with leading zeros01–12
GHour, 24-hour, without leading zeros0-23
HHour, 24-hour, with leading zeros00-23
iMinutes, with leading zeros00-59
sSeconds, with leading zeros00-59
TTimezone abbreviationEg., EST, MDT ...

Excluir una categoría de la página principal de wordpress

En el functions.php, agregar lo siguiente, cambiar el número o números de la o las categorías a excluir:


function excludeCat($query) {
  if ( $query->is_home ) {
    $query->set('cat', '-8,-12');
  }
  return $query;
}
add_filter('pre_get_posts', 'excludeCat');

martes, 21 de agosto de 2012

lunes, 20 de agosto de 2012

poner tweets sin twitter widget ni plugin

Éste es el código, donde dice Camilo_B2012 se cambia el nombre de usuario, también se pueden cambiar el número de tweets, etcétera. Simplemente pegar el código y después meterle todo el css.



<?php
/****************************CODE-1**************************************
* @Author: Boutros AbiChedid
* @Date:   May 30, 2012
* @Websites: bacsoftwareconsulting.com/ ; blueoliveonline.com/
* @Description: Display your Latest tweets (from your Twitter account) on
* your WordPress Blog.
* @Tested on: WordPress version 3.3.2
*************************************************************************/
?>
<div class="box">
<div class="box_title">Latest Tweets</div>
<div class="box_content">
    <?php
    //Path to include feed.php file located in wp-includes folder.
    include_once(ABSPATH . WPINC . '/feed.php');

    //Retrieves the feed and parses it. Specify the feed URL. This is my feed, put yours.
    $rss = fetch_feed('http://twitter.com/statuses/user_timeline/Camilo_B2012.rss');

    $tweetnumber = 4;  /** How many tweets you want to show. Must be >= 1 **/
    $maxitems = $rss->get_item_quantity($tweetnumber);

    $firstitem = 0; /** Specify the first item. 0 to start from the newest tweet. **/
    $rss_items = $rss->get_items($firstitem, $maxitems);
    ?>

    <div class="twitter-list">
        <ul>
        <?php
        if ($maxitems == 0)
                echo '<li>No Tweets Yet!</li>';
        else
        //Loop through each feed item and display it as a link.
        foreach ( $rss_items as $item ) { ?>
            <li>
            <!-- Get the tweet item title as an external link.-->
            <a href='<?php echo $item->get_permalink(); ?>' target="_blank" title="External Link&#8230;" rel="nofollow">
            <?php echo $item->get_title(); ?></a> <br />
            <!-- Get the tweet item date.-->
            <span><?php echo 'Posted: ' . $item->get_date(); ?></span>
            </li>
        <?php } ?>
        </ul>
    </div>
</div>

eso.

viernes, 10 de agosto de 2012

Usar theme-options en wordpress

Sin sabe nada de php pude poner unas theme-options en un template de wordpress. Me sirvieron estos dos manuales: éste http://www.webdesignerdepot.com/2012/02/creating-a-custom-wordpress-theme-options-page/, y éste http://themeshaper.com/2010/06/03/sample-theme-options/, desde donde bajas un php llamado theme-options.php, ese se pone en tu template, y se modifica para usar las opciones que se quiera.

yo uso las opciones que vienen por defecto, aunque camiándole las palabras, obvio.

Para usar el texto que hay en un cuadro de texto del theme-options, se hace hace así:


<?php
    $options = get_option('sample_theme_options');
    echo $options['NOMBREDELAOPCION'];
?>

O por ejemplo, para poner uno u otro div del template según si un check box del theme-options, así:


<?php if ($options['option1'] == 0) { ?>
<div id="introtext">
ASDFASDFASDFASDFASDF
</div>
<?php }else{ ?>
<div id="introtext">
2345234523452345234523452345234523452345
</div>
<?php } ?> 

el ==0 se puede cambiar por ==1 dependiendo de cómo esté planteada la opción.


Para usar los RadioInput, así:


<?php if ($options['radioinput'] == yes) { ?>
<div id="introtext">
ASDFASDFASDFASDFASDF
</div>
<?php } elseif ($options['radioinput'] == no){ ?>
<div id="introtext">
2345234523452345234523452345234523452345
</div>
<?php }elseif ($options['radioinput'] == maybe){ ?>
<div id="introtext">
MAUBE
</div>
<?php } ?> 

jueves, 9 de agosto de 2012

Poner una imagen de fondo que cubra siempre toda la ventana

La idea es que sin importar el tamaño  en que esté la ventana, la imagen siempre cubra la pantalla completa. Se hace así, yo lo pude en el body:


body {
background:url(img/fondo.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

Efecto cuático con sombras en CSS

La idea de todo esto es escribir un texto, y con :before y :after meter dos textos iguales, pero casi transparentes, puestos encima, y el primero moverlo 1px abajo de la derecha, y el siguiente moverlo 2 pixeles abajo a la derecha. Como son semitransparentes, van a cambiar el color del texto. El problema es que si el color de fondo donde aparecen las sombras no es oscuro, no se van a notar las sombras exteriores.

con este div:

<div class="tit" title="Esto y lo otro">Esto y lo otro</div>



y este CSS:

.tit {font-size: 80px;  padding: .5em 0; color:#black; font-weight:bold; position:relative;}
.tit:before, .tit:after  {content:attr(title); font-size: 80px; padding: .5em 0; position:absolute; color:rgba(255,255,225,0.1)}
.tit:before  { top:1px; left:1px; right:0;}
.tit:after  { top:2px; left:2px; right:0;}

martes, 7 de agosto de 2012

Poner la fecha de hoy en español con javascript

Primero se crea la función en el header:


<script language="JavaScript">
function Fecha()
{
meses = new Array("Enero","Febrero","Marzo","Abril","Mayo","Ju nio","Julio","Agosto","Septiembre","Octubre","Novi embre","Diciembre");
data = new Date();
index = data.getMonth();
diasemana=new Array("Lunes","Martes","Miércoles","Jueves","Viern es","Sábado","Domingo");
indexday = data.getDay();
if (indexday == 0)
indexday = 7;
any = data.getYear();
if (any < 1900)
any = 1900 + any;
document.write(diasemana[indexday-1]+ "," + ' '+data.getDate()+ " de " + meses[index] + " de " + any);
}
</script>

y donde quiero meter la fecha, le chanto:

<SCRIPT language=JavaScript>Fecha()</SCRIPT>

Indicadores económicos de Chile con javascript

Entera buena esta forma que encontré para poner la UF u otros indicadores económicos usando un documento .js que tienen el en BCI

el documento es este: http://www.bci.cl/common/include/valores.js

Pa sacar sólo la UF, pongo esto en el header:


     <script type="text/javascript" src="http://www.bci.cl/common/include/valores.js"></script>
    <script type="text/javascript">
function g(id){return document.getElementById(id);}
function valor(indice){return formatear_numero(arrValores[indice].valor2);}
window.onload=function(){
var uf=4;
if(typeof(arrValores)!="undefined"){
g('uf').innerHTML=valor(uf);
}
}
</script>


y donde quiero poner la UF, le chanto:


<span id="uf"></span>



la explicación entera está aquí:

Indicadores económicos con javascript

lunes, 6 de agosto de 2012

poner elementos encima de videos de youtube

no hace problema en todos los navegadores, pero si poner algún div sobre un video, el video se one encima y se ve feo. para solucionarlo en videos de youtube, hay que agregar el parámetro wmode=transparent en el código embed.

Por ejemplo, si este es tu código embed

<iframe width="315" height="242" src="http://www.youtube.com/embed/WV-Mr3t8uYQ" frameborder="0" allowfullscreen></iframe>

lo dejas así

<iframe width="315" height="242" src="http://www.youtube.com/embed/WV-Mr3t8uYQ?wmode=transparent" frameborder="0" allowfullscreen></iframe>

o sea, le agregas ?wmode=transparent después de la ruta del video.

sombra bacancita con CSS

metí un div con la clase cuadro, y le chanté este CSS, que quedó pulentito.


.cuadro:before {content: ""; position:absolute; background:transparent; width:90%; height:90%; z-index:-1; left:7%;
-webkit-box-shadow: 0px 10px 9px -2px rgba(0, 0, 0, 0.5);
box-shadow: 0px 10px 9px -2px rgba(0, 0, 0, 0.5);
transform:rotate(4deg);
-ms-transform:rotate(4deg); /* IE 9 */
-moz-transform:rotate(4deg); /* Firefox */
-webkit-transform:rotate(4deg); /* Safari and Chrome */
-o-transform:rotate(4deg); /* Opera */}
.cuadro {width:200px; height:100px; margin:40px 0; background:orange; position:relative; }
.cuadro:after {content: ""; position:absolute; background:transparent; width:90%; height:90%; z-index:-1; left:3%;
-webkit-box-shadow: 0px 10px 9px -2px rgba(0, 0, 0, 0.5);
box-shadow: 0px 10px 9px -2px rgba(0, 0, 0, 0.5);
transform:rotate(-4deg);
-ms-transform:rotate(-4deg); /* IE 9 */
-moz-transform:rotate(-4deg); /* Firefox */
-webkit-transform:rotate(-4deg); /* Safari and Chrome */
-o-transform:rotate(-4deg); /* Opera */}

miércoles, 1 de agosto de 2012

compartir post de wordpress en facebook

La cosa es tomar el código que te entrega facebook, y cambiar el data-href por el post, obvio que dentro del loop:

así:  <div class="fb-like" data-href="<?php the_permalink(); ?>" data-send="false" data-layout="button_count" data-width="450" data-show-faces="false" data-action="recommend"></div>

y no olvidar poner lo siguiente en el header:

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/es_LA/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

twittear un post de wordpress

Sólo hay que meter lo siguiente en el loop


<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
<a href="http://twitter.com/share" class="twitter-share-button"
data-url="<?php the_permalink(); ?>"
data-via="Camilo_B2012"
data-text="<?php the_title(); ?>"
data-count="horizontal">Tdd</a>


en data-url está el link al post de wordpress que estás tweeteando
en data-via, se pone el usuario desde el que se tuitea la cuestión
en data-text, está el título del post, se puede agregar algo más
en data-count, se puede poner vertical, horizontal o none.
el texto del a href, aunque lo trato de cambiar, sigue diciendo "Tweet", así que filo

Ejemplo de uso de setInterval, if, else if, y nth-child en jQuery

he aquí el ejemplo que funciona perfect en wordpress


<script type="text/javascript">
$(document).ready(function(){


setInterval(function(){
if ( $(".noticiasSlider .post:nth-child(1)").css("display")   == "block" ){
$(".menuSlider span").css("background", "#a99e93");
$(".menuSlider span:nth-child(2)").css("background", "#227090");$(".noticiasSlider .post").fadeOut('slow');
$(".noticiasSlider .post:nth-child(2)").fadeIn('slow');
}
else if ( $(".noticiasSlider .post:nth-child(2)").css("display")   == "block" ){
$(".menuSlider span").css("background", "#a99e93");
$(".menuSlider span:nth-child(3)").css("background", "#227090");$(".noticiasSlider .post").fadeOut('slow');
$(".noticiasSlider .post:nth-child(3)").fadeIn('slow');
}
else if ( $(".noticiasSlider .post:nth-child(3)").css("display")   == "block" ){
$(".menuSlider span").css("background", "#a99e93");
$(".menuSlider span:nth-child(4)").css("background", "#227090");$(".noticiasSlider .post").fadeOut('slow');
$(".noticiasSlider .post:nth-child(4)").fadeIn('slow');
}
else if ( $(".noticiasSlider .post:nth-child(4)").css("display")   == "block" ){
$(".menuSlider span").css("background", "#a99e93");
$(".menuSlider span:nth-child(1)").css("background", "#227090");
$(".noticiasSlider .post").fadeOut('slow');
$(".noticiasSlider .post:nth-child(1)").fadeIn('slow');
}
},3000);

      });
</script>

usar los campos personalizados de wordpress

Hay que poner el siguiente código dentro del loop:

<?php echo get_post_meta($post->ID, XXXXXXX, true); ?>


Evidentemente, hay que cambiar las XXXXX por el nombre que le diste al campo perzonalizado.

jueves, 19 de julio de 2012

súper simple manera de obtener los seguidores de un usuario de twitter

Es cosa de poner lo siguiente en cualquier parte del template, donde dice USUARIO, hay que poner el nombre del usuario sin el @.

<?php
function GetFollowes($user){
    $xml=simplexml_load_file("http://twitter.com/users/show.xml?screen_name=$user");
    return $xml->followers_count;
}

echo GetFollowes('USUARIO');
?>