(SOLVED) How to center div horizontally and vertically using jQuery

How to center a div horizontally and vertically, no matter if the browser screen is resized?

It is very easy with jQuery…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 	<meta http-equiv="Content-Language" content="es" />
 	<title>Center div horizontally and vertically</title>
 	<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<script type="text/javascript">
		jQuery.fn.center = function () {
    		  this.css("position","absolute");
    		  this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px");
    		  this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
    		return this;
		}
		$(window).load(function(){  
			$("#container").center();
		});
		$(window).resize(function(){
			$("#container").center();
		});
	</script>
</head>
<body>	
<div id="container">
	<span>Some content here</span>
</div>
</body>
</html>

Pasar de .mo a .pot y viceversa [RESUELTO]

Algo común cuando instalas un theme de WordPress es que en el path donde se encuentren las traducciones sólo tengas el archivo .mo correspondiente a tu idioma (y no el .po).

Los archivos .mo son binarios y no se pueden editar directamente. Asi que, ¿cómo modificar un archivo de traducción si no tienes el archivo .po correspondiente?

Fácil. En la página http://tools.konstruktors.com/ te ofrecen una herramienta online gratuita para realizar conversiones de .po a .mo y conversiones de .mo a .po

Si lo prefieres, también puedes instalar en tu equipo las gettext-tools y usar la herramienta msgunfmt.

RESUELTO – Internet Explorer (IE7, IE8, IE9, IE10, IE11) en MAC (OS X)

Muchas veces nos vemos en la obligación de probar cómo se ve una web en Internet Explorer. Inexplicablemente, todavía hay muchos usuarios que emplean Internet Explorer en sus versiones más antiguas (IE6, IE7, IE8, IE9), pese a las obvias desventajas de elegir este navegador.

Internet Explorer en MAC OSX

Desde Windows resulta más sencillo. Pero, ¿cómo ejecutar Internet Explorer desde tu OS X (Mac)?

La solución es sencilla:

1. Instala VirtualBox (descargar el instalador de VirtualBox para OSX)

2. Decide qué versiones de IE quieres instalar, abre Terminal y escribe el comando adecuado en función a la versión que desees *
— Todas las versiones de IE (crearás tantas máquinas virtuales como versiones de IE se instalen)

curl -s https://raw.githubusercontent.com/xdissent/ievms/master/ievms.sh | bash

— Internet Explorer 7 (IE7):

curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS="7" bash

— Internet Explorer (IE8):

curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS="8" bash

— Internet Explorer (IE9):

curl -s https://raw.githubusercontent.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS="9" bash

— Internet Explorer (IE10):

curl -s https://raw.githubusercontent.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS="10" bash

— Internet Explorer (IE11):

curl -s https://raw.githubusercontent.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS="11" bash

3. Abre VirtualBox (lo tendrás instalado en “Aplicaciones” > “Virtual Box”) e inicia la máquina virtual adecuada. Se iniciará Windows y tendrás la versión de Internet Explorer que elegiste disponible. Recuerda que la contraseña por defecto de Windows es “Password1”.
Además, puedes realizar un snapshot de las máquinas para “solventar” el problema de la licencia de evaluación de 30 días que Microsoft aplica a su SO. Crea un snapshot nada más instalar las máquinas virtuales y arráncalo. Asi siempre tendrás tus 30 días de evaluación restantes.

Internet Explorer en Mac (resuelto)

* Los comandos del paso 2 son parte del ievsms script de xdissent y se encargan del proceso completo de descarga, conversión e instalación. Más fácil no puede ser 🙂

Nota: Si las URL’s de arriba no funcionan correctamente, puede ser que github haya cambiado la estructura de URL’s de raw.github.com a raw.githubusercontent.com. Corrige las URL’s superiores según este patrón.

Adding jQuery UI tabs to Drupal 7 [SOLVED]

I recently wanted to add some jQuery UI tabs to nodes. Drupal 7 has jQuery 1.4 included in core, so we’ll take advantage of that.

This is how you do it:

First, edit template.php and create / make some changes to hook _preprocess_html.

function THEMENAME_preprocess_html(&$variables){
   // This function looks for node 1 and only adds the javascript for this.
   // However it can be extended in different ways if required
    drupal_add_library('system', 'ui.tabs');
    drupal_add_js('jQuery(document).ready(function(){
                jQuery("#tabs").tabs({event: "mouseover"});
                jQuery("#tabs").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
                jQuery("#tabs li").removeClass("ui-corner-top").addClass("ui-corner-left");
            });',
        'inline');
}

*Note that you can remove ui-tabs-vertical if you want horizontal tabs. You can also change the mouseover event to the event you prefer.

This would be the markup:

<!-- TITULOS PESTAÑAS -->
<div id="tabs">
<div id="tab-list">
  <ul>
  <li><a href="#tabs-1">Titulo 1</a></li>
  <li><a href="#tabs-2">Titulo 2</a></li>
  <li><a href="#tabs-3">Titulo 3</a></li>
  <li><a href="#tabs-4">Titulo 4</a></li>
  <li><a href="#tabs-5">Titulo 5</a></li>
  <li><a href="#tabs-6">Titulo 6</a></li>
  <li><a href="#tabs-7">Titulo 7</a></li>
  <li><a href="#tabs-8">Titulo 8</a></li>
  <li><a href="#tabs-9">Titulo 9</a></li>
  <li><a href="#tabs-10">Titulo 10</a></li>
  </ul>
</div>
 
 
<!-- CONTENIDO PESTAÑAS -->
<div id="tab-content">    
  <div id="tabs-1">
    <p>Texto de la TABS-1</p>
  </div>
  <div id="tabs-2">
    <p>Texto de la TABS-2</p>
  </div>
  <div id="tabs-3">
    <p>Texto de la TABS-3</p>
  </div>
  <div id="tabs-4">
    <p>Texto de la TABS-4</p>
  </div>
  <div id="tabs-5">
    <p>Texto de la TABS-5</p>
  </div>
  <div id="tabs-6">
   <p>Texto de la TABS-6</p>
  </div>
  <div id="tabs-7">
    <p>Texto de la TABS-7</p>
  </div>
  <div id="tabs-8">
    <p>Texto de la TABS-8</p>
  </div>
  <div id="tabs-9">
    <p>Texto de la TABS-9</p>
  </div>
  <div id="tabs-10">
    <p>Texto de la TABS-10</p>
  </div>
</div>
</div>

And a sample output:
UI-Tabs-Drupal

Drupal 7: quick-edit link for nodes for authorized users [SOLVED]

Showing a “edit this node” link for users who have authorization to edit that node is a useful feature.

The link will show only to logged users who have the editing privilege.

In Drupal7 this can be done by editing the node template and adding these lines to your node.tpl.php (or node–contenttypename-tpl.php)

  <!-- quick edit link -->
  <?php if(user_access('administer nodes')): 
      echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
   endif; ?>
  <!-- /quick edit link -->

Or:

<?php
if (node_access('update',$node)){
   print l(t('Edit'),'node/'.$node->nid.'/edit' );
}
?>

Add Masonry container template to WordPress RYU THEME [SOLVED]

Some days ago I wrote a post about adding a masonry container to Ryu theme.

Today I would like to explain how to add a masonry container template to your Ryu Theme.

My template will ouput images related to categories (I used the Tejus Category Image plugin to link images to categories) displayed in a masonry wrapper.

First, we’ll have to make the template archive (which you will put in /wp-content/themes/ryu/template-art-lfa.php)

<?php
// File Security Check
if ( ! empty( $_SERVER['SCRIPT_FILENAME'] ) && basename( __FILE__ ) == basename( $_SERVER['SCRIPT_FILENAME'] ) ) :
	die ( 'You do not have sufficient permissions to access this page!' );
endif;
 
/* Template Name: art-lfa */
 
get_header(); ?>
 
<div id="boxes"> <!-- masonry wrapper -->
 
	<?php
	$categorias = get_categories('child_of=2'); // I am getting the subcategories of category with ID=2
	foreach ($categorias as $categoria){
		?>
 
        <div id="categoria-<?php echo $categoria->cat_ID; ?>" class="box">
               <a href="<?php echo get_category_link($categoria->cat_ID); ?> ">
		          <div class="rel">
			        	<img src="<?php echo tejus_dj_getcatimg($categoria->cat_ID); ?>" 
					     	class="attachment-summary-image wp-post-image" 
					     	style="width: 350px; "
					     	alt="<?php echo $categoria->cat_name ?>" />
 
			         	<div class="texts" style="height:100%">
				          	<div class="abs">
								<?php echo $categoria->cat_name; ?>
						</div>
			         	</div>
		           </div>
               </a>
	</div>
	<?php
	} // foreach 
    ?>	  				
</div><!-- del masonry-wrapper -->
<div class="clear"></div>
 
<?php get_footer(); ?>

We will also need some CSS. So, edit /wp-content/themes/ryu/style.css and add these lines at the end of the file:

/* miguel nuevo layout masonry (#boxes) */
#boxes { margin-top: 40px; margin-left: auto; margin-right: auto; }
.box { width: 350px; margin-bottom: 15px; color: #636363; /* para alto fijo: quitar si masonry...  float:left;*/}
.box .rel { position: relative; }
.box .rel p { margin: 0; }
.box .texts { /*position: absolute; top: -20px; left: -20px; width: 450px; color: #fff; z-index: 200;*/color: #FFFFFF;left: 0;position: absolute; top: 0px; width: 460px; z-index: 200; opacity: 0; filter: alpha(opacity=0); }
.box .texts .categories a, .box .texts a, .box .texts .posted, .box .texts .posted a { color: #fff; }
.box .texts .transparent img { opacity: 0.7; filter: alpha(opacity=10); }
.box .texts .abs { position: absolute; top: 50%; width: 100%; text-align: center;}
.box .categories { padding-bottom: 10px; }
.box .categories a, .box .posted a { color: #a1a1a1; }
.box h1 { margin: 0; padding-bottom: 10px; font-size: 16px; }
.box h1 a { color: #333; }
.box .posted { padding-top: 10px; color: #a1a1a1; }
.box img { display: block;
margin-left: auto;
margin-right: auto; }
.box img:hover {opacity: '0.7' filter: 'alpha(opacity=70)'}

Then you will need to use ImagesLoaded (http://imagesloaded.desandro.com/) to avoid some issues with Chrome and Safari. If you do not add this JS file, masonry will be triggering BEFORE images have been fully loaded and will fail in Chrome.

So, first of all you should download imagesloaded.pkgd.min.js and put it into /wp-content/themes/ryu/js/imagesloaded.pkgd.min.js.

Ok, now we have to tell Ryu to use ImagesLoaded. So we’ll need to edit /wp-content/themes/ryu/functions.php to register this new script (pay attention to core_mods function)
Here is my functions.php after doing so:

<?php
/**
 * Ryu functions and definitions
 *
 * @package Ryu
 */
 
 
 /* previa: para archivos cargo cosas del tema gridly */
 // Load jQuery
	if ( !function_exists('core_mods') ) {
		function core_mods() {
			if ( !is_admin() ) {
				wp_deregister_script('jquery');
				wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"));
				wp_register_script('jquery.masonry', (get_template_directory_uri()."/js/jquery.masonry.min.js"),'jquery',false,true);
 
                // nuevo 20140112 para evitar problemas imagenes en chrome... https://github.com/desandro/masonry/issues/35
				wp_register_script('imagesloaded.pkgd.min.js', (get_template_directory_uri()."/js/functions.js"), 'imagesloaded.pkgd', false,true);
				// ------------------------
 
				wp_register_script('gridly.functions', (get_template_directory_uri()."/js/functions.js"),'jquery.masonry',false,true);
 
				wp_enqueue_script('jquery');
				wp_enqueue_script('jquery.masonry');
 
				// nuevo 20140112 para evitar problemas imgs chrome...
				wp_enqueue_script('imagesloaded.pkgd');
				// ---------------------------------
 
 
				wp_enqueue_script('gridly.functions');
			}
		}
		core_mods();
	}
 
 
	// Gridly post thumbnails
	add_theme_support( 'post-thumbnails' );
	add_image_size('summary-image', 310, 9999);
	add_image_size('detail-image', 770, 9999);
 
 
    // hide blank excerpts 
	function custom_excerpt_length( $length ) {
	return 0;
	}
	add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
 
	function new_excerpt_more($more) {
       global $post;
	return '';
	}
	add_filter('excerpt_more', 'new_excerpt_more');
 
 
 
 /* EMPIEZA FUNCTIONS DEL TEMA RYU.... */
 
/**
 * Set the content width based on the theme's design and stylesheet.
 */
if ( ! isset( $content_width ) )
	$content_width = 696; /* pixels */
 
if ( ! function_exists( 'ryu_setup' ) ) :
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which runs
 * before the init hook. The init hook is too late for some features, such as indicating
 * support post thumbnails.
 */
function ryu_setup() {
	/**
	 * Make theme available for translation
	 * Translations can be filed in the /languages/ directory
	 * If you're building a theme based on ryu, use a find and replace
	 * to change 'ryu' to the name of your theme in all the template files
	 */
	load_theme_textdomain( 'ryu', get_template_directory() . '/languages' );
 
	/**
	 * Add default posts and comments RSS feed links to head
	 */
	add_theme_support( 'automatic-feed-links' );
 
	/**
	 * Enable support for Post Thumbnails
	 */
	add_theme_support( 'post-thumbnails' );
 
	/**
	 * Adding several sizes for Post Thumbnails
	 */
	add_image_size( 'ryu-featured-thumbnail', 1272, 0 );
 
	/**
	 * This theme uses wp_nav_menu() in one location.
	 */
	register_nav_menus( array(
		'primary' => __( 'Primary Menu', 'ryu' ),
	) );
 
	/**
	 * Enable support for Post Formats
	 */
	add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link', 'gallery' ) );
 
	/**
	 * Enable support for the Tonesque library
	 */
	add_theme_support( 'tonesque' );
}
endif; // ryu_setup
add_action( 'after_setup_theme', 'ryu_setup' );
 
/**
 * Setup the WordPress core custom background feature.
 *
 * Hooks into the after_setup_theme action.
 */
function ryu_register_custom_background() {
	add_theme_support( 'custom-background', apply_filters( 'ryu_custom_background_args', array(
		'default-color' => 'fff',
		'default-image' => '',
	) ) );
}
add_action( 'after_setup_theme', 'ryu_register_custom_background' );
 
/**
 * Register widgetized area and update sidebar with default widgets
 */
function ryu_widgets_init() {
	register_sidebar( array(
		'name'          => __( 'Top Widget Area One', 'ryu' ),
		'id'            => 'sidebar-1',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h1 class="widget-title">',
		'after_title'   => '</h1>',
	) );
 
	register_sidebar( array(
		'name'          => __( 'Top Widget Area Two', 'ryu' ),
		'id'            => 'sidebar-2',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h1 class="widget-title">',
		'after_title'   => '</h1>',
	) );
 
	register_sidebar( array(
		'name'          => __( 'Top Widget Area Three', 'ryu' ),
		'id'            => 'sidebar-3',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h1 class="widget-title">',
		'after_title'   => '</h1>',
	) );
 
	register_sidebar( array(
		'name'          => __( 'Top Widget Area Four', 'ryu' ),
		'id'            => 'sidebar-4',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h1 class="widget-title">',
		'after_title'   => '</h1>',
	) );
}
add_action( 'widgets_init', 'ryu_widgets_init' );
 
/**
 * Register Google fonts for Ryu
 */
function ryu_fonts() {
	/* translators: If there are characters in your language that are not supported
	   by Lato, translate this to 'off'. Do not translate into your own language. */
	if ( 'off' !== _x( 'on', 'Lato font: on or off', 'ryu' ) ) {
 
		$protocol = is_ssl() ? 'https' : 'http';
 
		wp_register_style( 'ryu-lato', "$protocol://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic", array(), null );
	}
 
	/* translators: If there are characters in your language that are not supported
	   by Playfair Display, translate this to 'off'. Do not translate into your own language. */
	if ( 'off' !== _x( 'on', 'Playfair Display font: on or off', 'ryu' ) ) {
		$subsets = 'latin,latin-ext';
 
		/* translators: To add an additional Playfair Display character subset specific to your language, translate this to 'cyrillic'. Do not translate into your own language. */
		$subset = _x( 'no-subset', 'Playfair Display font: add new subset (cyrillic)', 'ryu' );
 
		if ( 'cyrillic' == $subset )
			$subsets .= ',cyrillic';
 
		$protocol = is_ssl() ? 'https' : 'http';
		$query_args = array(
			'family' => 'Playfair+Display:400,700,900,400italic,700italic,900italic',
			'subset' => $subsets,
		);
		wp_register_style( 'ryu-playfair-display', add_query_arg( $query_args, "$protocol://fonts.googleapis.com/css" ), array(), null );
	}
}
add_action( 'init', 'ryu_fonts' );
 
/**
 * Enqueue scripts and styles
 */
function ryu_scripts() {
	wp_enqueue_style( 'ryu-style', get_stylesheet_uri() );
 
	wp_enqueue_style( 'ryu-lato' );
 
	wp_enqueue_style( 'ryu-playfair-display' );
 
	if ( has_nav_menu( 'primary' ) )
		wp_enqueue_script( 'ryu-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true );
 
	wp_enqueue_script( 'ryu-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20130115', true );
 
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) )
		wp_enqueue_script( 'comment-reply' );
 
	if ( is_singular() && wp_attachment_is_image() )
		wp_enqueue_script( 'ryu-keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20120202' );
 
	wp_enqueue_script( 'ryu-theme', get_template_directory_uri() . '/js/ryu.js', array( 'jquery' ), '20130319', true );
}
add_action( 'wp_enqueue_scripts', 'ryu_scripts' );
 
/**
 * Enqueue Google fonts style to admin screen for custom header display.
 */
function ryu_admin_fonts( $hook_suffix ) {
	if ( 'appearance_page_custom-header' != $hook_suffix )
		return;
 
	wp_enqueue_style( 'ryu-lato' );
 
	wp_enqueue_style( 'ryu-playfair-display' );
}
add_action( 'admin_enqueue_scripts', 'ryu_admin_fonts' );
 
/**
 * Count the number of footer sidebars to enable dynamic classes for the footer
 */
function ryu_top_sidebar_class() {
 
	$count = 0;
 
	if ( is_active_sidebar( 'sidebar-1' ) )
		$count++;
 
	if ( is_active_sidebar( 'sidebar-2' ) )
		$count++;
 
	if ( is_active_sidebar( 'sidebar-3' ) )
		$count++;
 
	if ( is_active_sidebar( 'sidebar-4' ) )
		$count++;
 
	$class = '';
 
	switch ( $count ) {
		case '1':
			$class = 'one';
			break;
		case '2':
			$class = 'two';
			break;
		case '3':
			$class = 'three';
			break;
		case '4':
			$class = 'four';
			break;
	}
 
	if ( $class )
		echo 'class="wrap clear ' . $class . '"';
}
 
/**
 * Implement Tonesque if need be
 */
function ryu_load_bundled_tonesque() {
	if ( ! class_exists( 'Tonesque' ) ) {
		require( get_template_directory() . '/inc/tonesque.php' );
	}
}
 
 
/* 20131226 Miguel para añadir la parte de contributors... */
function contributors() {
	global $wpdb;
 
	$authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users ORDER BY display_name");
 
	foreach($authors as $author) {
		echo '<li><div class="authorinfo" style="width: 100%;"">';
		/*echo "<a href=\"".get_bloginfo('url')."/?author=";
		echo $author->ID;
		echo "\">";*/
		//echo get_avatar($author->ID);
 
		echo '<div class="authorphoto">';
		if (function_exists('userphoto')){
			echo userphoto($author->ID); // requiere plugin User Photo para WP
		}
		else{
			echo get_avatar($author->ID);
		}
		echo '</div>';
		echo '<div class="authorbio"><h4>';
		the_author_meta('display_name', $author->ID);
		echo "</h4>";
		echo '<p>';
		the_author_meta('user_description', $author->ID);
		echo '</p>';
		echo "</div>";
		echo "</div></li>";
	}
 
    /* example output */
    /*echo '
    		<div class="authorinfo" style="width: 100%;"">
    			<div class="authorphoto" style="float: left; width: 25%; max-width: 200px; margin-right: 5%; position: relative;">
 
    			</div>
    			<div class="authorbio" style="float: left; width: 70%; max-width: 740px; position: relative">
    				<h4>Nombre</h4>
    				<p style="font-size:0.7em">Esta es la descripcion del autor en funcion contributors() de functinons.php...</p>
    			</div>
    		</div>
    	  ';*/
 
}
/* fin contributors */
 
 
 
 
add_action( 'wp_loaded', 'ryu_load_bundled_tonesque' );
 
/**
 * Implement the Custom Header feature
 */
require get_template_directory() . '/inc/custom-header.php';
 
/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';
 
/**
 * Custom functions that act independently of the theme templates
 */
require get_template_directory() . '/inc/extras.php';
 
/**
 * Customizer additions
 */
require get_template_directory() . '/inc/customizer.php';
 
/*
 * Load Jetpack compatibility file.
 */
require get_template_directory() . '/inc/jetpack.php';
 
 
// updater for WordPress.com themes
if ( is_admin() )
	include dirname( __FILE__ ) . '/inc/updater.php';

Next we need to tell Ryu to render the masonry wrapper when all images in our container are fully loaded. ImagesLoaded triggers an event when this happens. So we will just edit /wp-content/themes/ryu/js/functions.js and add these to the end of the file…

// initialize Masonry after all images have loaded  .. EVITAR PROBLEMAS CHROME!!!
// ver mas aqui https://github.com/desandro/masonry/issues/35
 
var $container = $('#boxes');
$container.imagesLoaded( function() {
 
// grid
	$('#boxes').masonry({
		itemSelector: '.box',
		columnWidth: 350,
		isFitWidth: true, 
		gutterWidth: 20	
	});
 
	$('#related').masonry({
		itemSelector: '.box',
		columnWidth: 350,
		isFitWidth: true, 
		gutterWidth: 20	
	});
 
	$('.texts').live({
		'mouseenter': function() {
			//if ($(this).height() < $(this).find('.abs').height()) {
			//	$(this).height($(this).find('.abs').height());
			//}
 
			$(this).stop(true, true).animate({
				'opacity': '0.8',
				'filter': 'alpha(opacity=80)'
			}, 0);
		},
		'mouseleave': function() {
			$(this).stop(true, true).animate({
				'opacity': '0',
				'filter': 'alpha(opacity=0)'
			}, 0);
		}
	});
});

The last step is easy: create a new page (Pages>New Page) and tell it to use the template-art-lfa template we just made.

You can download my ryu-completo-masonry-ok-20140112.

Enjoy!

Drupal7: list allowed values from a field type list [SOLVED]

In Drupal 7, how do you list all the allowed values in a certain field of some content type?

You can use the list_allowed_values function.

Lets see it with an example.

I will define a new Content Type called “Actividad” (machine name=’actividad‘), which will have a title, a body and a List(text) field type called ‘tipo_actividad‘ (machine name=’field_tipo_actividad‘):
list_allowed_values drupal 7

And then I will define the allowed values for this field_tipo_actividad field:
drupal 7 list_allowed_values for field

Now, how do I programmatically list the allowed values for that field? Using list_allowed_values function:

$field = field_info_field('field_tipo_actividad'); /* field_tipo_actividad=machine name of the field */
$allowed_values = list_allowed_values($field);     /* what are the values allowed for that field? */
return var_dump($allowed_values);

drupal7 list allowed values

If you want a prettier output, you can change the code to:

$field = field_info_field('field_tipo_actividad');
$allowed_values = list_allowed_values($field);
$salida = "";
foreach ($allowed_values as $key=>$value){
    $salida = $salida."Key: ".$key." Value: ".$value."<br />";
}
return $salida;

And you’ll get something like:
drupal list_allowed_values tutorial example

WordPress: adding masonry grid layout to Ryu theme [SOLVED]

I just love Ryu theme for WordPress. It is a modern, white, minimal yet elegant theme.

The one thing I am not fond of about Ryu is the archive page. I would prefer if it had a grid-based layout (using masonry, for instance). For instance, something like the Gridly theme.

So I will be teaching you how make this posible. If you don’t need so many explanations and are only interested in CSS+markup, you can just read this.

Include masonry and jQuery (if not included) in /wp-content/themes/ryu-wpcom (you can also link to them in http://ajax.googleapis.com/ajax/libs/jquery site)

Then edit /wp-content/themes/ryu-wpcom/functions.php file and add these lines after the <?php tag.

The most important function is the first one. The necessary javascript files are included (jquery.min.js will be linked to google’s website and jquery.masonry.min.js will be loaded from the js folder in the theme, /wp-content/themes/ryu-wpcom/js/). Note that there is also this /js/functions.js file which contents will be defined later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* functions.php, just after php code starts */
 // Load jQuery
	if ( !function_exists('core_mods') ) {
		function core_mods() {
			if ( !is_admin() ) {
				wp_deregister_script('jquery');
				wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"));
				wp_register_script('jquery.masonry', (get_template_directory_uri()."/js/jquery.masonry.min.js"),'jquery',false,true);
				wp_register_script('gridly.functions', (get_template_directory_uri()."/js/functions.js"),'jquery.masonry',false,true);
 
				wp_enqueue_script('jquery');
				wp_enqueue_script('jquery.masonry');
				wp_enqueue_script('gridly.functions');
			}
		}
		core_mods();
	}
 
	// Gridly post thumbnails
	add_theme_support( 'post-thumbnails' );
	add_image_size('summary-image', 310, 9999);
	add_image_size('detail-image', 770, 9999);
 
 
    // hide blank excerpts 
	function custom_excerpt_length( $length ) {
	return 0;
	}
	add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
 
	function new_excerpt_more($more) {
          global $post;
	  return '';
	}
	add_filter('excerpt_more', 'new_excerpt_more');

Now lets create the referenced /js/functions.js file with this contents (first lines are the ones you can find in gridly theme, so just pay attention to last part, lines 57-61, which is the code we just included):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// this is /js/functions.js (should be placed in your theme's folder, as in /wp-content/themes/ryu-wpcom/js/functions.js)
// masonry code 
$(document).ready(function() {
  $('#post-area').masonry({
    // options
    itemSelector : '.post',
    // options...
  isAnimated: true,
  animationOptions: {
    duration: 400,
    easing: 'linear',
    queue: false
  }
 
  });
});
 
// hover code for index  templates
$(document).ready(function() {
 
		$('#post-area .image').hover(
			function() {
				$(this).stop().fadeTo(300, 0.8);
			},
			function() {
				$(this).fadeTo(300, 1.0);
			}
		);	
 
 
});
 
// comment form values
$(document).ready(function(){
	$("#comment-form input").focus(function () {
		var origval = $(this).val();	
		$(this).val("");	
		//console.log(origval);
		$("#comment-form input").blur(function () {
			if($(this).val().length === 0 ) {
				$(this).val(origval);	
				origval = null;
			}else{
				origval = null;
			};	
		});
	});
});
 
// clear text area
$('textarea.comment-input').focus(function() {
   $(this).val('');
});
 
 
// mi llamada "a mano" a masonry
$(document).ready(function() {
	$('#masonry-wrapper').masonry({ 
	singleMode: true, 
  });
});

Now, two options:

1) If we want all kind of post archives (no matter which category) to be displayed with the grid layout: modify archive.php (/wp-content/themes/ryu-wpcom/archive.php)

2) If we want only some kind of post archives (specific category) to be displayed with the grid layout, and every other kind of post archive displayed with the theme native’s archive.php, then create a category-.php file…

(read this for further help)

I am using the second option. Archive from posts asigned to category ID=3 (named “producto“) will be displayed using masonry-grid-layout and every other archive will be displayed using theme’s native archive layout. So I create a new category-3.php file containing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
/**
 * The template for displaying Archive pages of posts asigned to category ID=3.
 *
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 * http://www.leccionespracticas.com/informatica-web/wordpress/wordpress-custom-archive-specific-category-solved/
 *
 * @package Ryu
 */
 
get_header(); ?>
 
	<section id="primary" class="content-area">
		<div id="content" class="site-content" role="main">
 
		<?php if ( have_posts() ) : ?>
 
			<header class="page-header"  style="display:none;>
				<div class="wrap">
					<h1 class="page-title"">
						<?php
							if ( is_category() ) :
								printf( __( 'Category Archives: %s', 'ryu' ), '<span>' . single_cat_title( '', false ) . '</span>' );
 
							elseif ( is_tag() ) :
								printf( __( 'Tag Archives: %s', 'ryu' ), '<span>' . single_tag_title( '', false ) . '</span>' );
 
							elseif ( is_author() ) :
								the_post();
								printf( __( 'Author Archives: %s', 'ryu' ), '<span class="vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '" title="' . esc_attr( get_the_author() ) . '" rel="me">' . get_the_author() . '</a></span>' );
								rewind_posts();
 
							elseif ( is_day() ) :
								printf( __( 'Daily Archives: %s', 'ryu' ), '<span>' . get_the_date() . '</span>' );
 
							elseif ( is_month() ) :
								printf( __( 'Monthly Archives: %s', 'ryu' ), '<span>' . get_the_date( 'F Y' ) . '</span>' );
 
							elseif ( is_year() ) :
								printf( __( 'Yearly Archives: %s', 'ryu' ), '<span>' . get_the_date( 'Y' ) . '</span>' );
 
							elseif ( is_tax( 'post_format', 'post-format-aside' ) ) :
								_e( 'Asides', 'ryu' );
 
							elseif ( is_tax( 'post_format', 'post-format-image' ) ) :
								_e( 'Images', 'ryu');
 
							elseif ( is_tax( 'post_format', 'post-format-video' ) ) :
								_e( 'Videos', 'ryu' );
 
							elseif ( is_tax( 'post_format', 'post-format-quote' ) ) :
								_e( 'Quotes', 'ryu' );
 
							elseif ( is_tax( 'post_format', 'post-format-link' ) ) :
								_e( 'Links', 'ryu' );
 
							else :
								_e( 'Archives', 'ryu' );
 
							endif;
						?>
					</h1>
					<?php
						// Show an optional term description.
						$term_description = term_description();
						if ( ! empty( $term_description ) ) :
							printf( '<div class="taxonomy-description">%s</div>', $term_description );
						endif;
					?>
				</div>
			</header><!-- .page-header -->
 
			<?php /* Start the Loop */ ?>
            <div id="masonry-wrapper">
			  <?php while ( have_posts() ) : the_post(); ?>
				<?php
					/* Include the Post-Format-specific template for the content.
					 * If you want to overload this in a child theme then include a file
					 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
					 */
					get_template_part( 'content', 'producto' );
				?>
			  <?php endwhile; ?>
            </div><!-- del masonry-wrapper -->
            <div class="clear"></div>
 
 
			<?php ryu_content_nav( 'nav-below' ); ?>
 
		<?php else : ?>
 
			<?php get_template_part( 'no-results', 'archive' ); ?>
 
		<?php endif; ?>
 
		</div><!-- #content -->
	</section><!-- #primary -->
 
<?php get_footer(); ?>

Pay attention to lines 73-84 and specially to line 81, in which we call get_template_part(). This call makes the need for creating a new content-producto.php file, containing:

<?php
/**
 * @package Ryu
 * this is content-producto.php
 */
?>
 
<div id="post-<?php the_ID(); ?>" class="boxy">
		 <?php if ( has_post_thumbnail() ) { ?>
         <div class="gridly-image"><a href="<?php the_permalink() ?>"><?php the_post_thumbnail( 'summary-image' );  ?></a></div>
 
		  <?php } ?>
       			<div class="gridly-copy"><h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
         <?php the_excerpt(); ?> 
 
         </div>
</div>

And then just edit the style.css file to add some CSS rules (in my case, 4 column masonry-grid):

/* el contenedor de masonry ocupará el 95% del área y dejará un margen del 2.5% */
#masonry-wrapper {
    margin-bottom: 2.5%;
    margin-left: 2.5%;
    margin-top: 2.5%;
    width: 95%;
}
 
/* en una "línea" del contenedor habrá 4 posts, cada uno ocupando el 24.8% y un margen por la derecha de 0.1% */
#masonry-wrapper .boxy{
	  width: 24.8%;
      margin-right: 0.1%;
      margin-bottom: 0.1%;
}

You can also download a full example of the theme (not depurated, just a project I am currently doing) here Ryu-theme-with-Grid-Layout

WordPress custom archive for specific category [SOLVED]

This days i’ve been designing a website in which there is a need for different archive views for each category of posts.

For this example, we will asume that we have three post categories defined:
1) uncategorized
2) blog
3) product

First thing is to find the category ID’s. You can do this by going to Posts > Categories and hovering your mouse over the ‘Edit’ link next to each category and pay attention to which URL it points to. In my example, for ‘product’ category I get this link:
http://www.mysite.com/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=3&post_type=post.

This means that product category has id number 3.

Knowing this, how do we make a wordpress archive for specific category of posts?

– Clone the (general purpose) archive.php in your theme folder. Name it category-.php, with being the category you want to customize it for. For instance, category-3.php
– Edit category-3.php and add the custom code.

You can read more about WordPress template hierarchy here.

WordPress and qTranslate: translate menu items

If you have installed qTranslate for the first time in your blog, and you already had a navigation menu with some items, what is the best way to translate those navigation items?

I have found that the easiest way to achieve this is by using some SQL (or phpMyAdmin) to directly modify the values in the database.

Follow this steps:

– open your phpMyAdmin to manage the DB
– go to table wp_posts and click on the Search link
– make a backup :), then
– filter by post_type=nav_menu_item
– look for the non translated records (field post_title)
– modify the field, ie: ‘My menu label in italian’ becomes ‘My menu label in italianMy menu label in english

An example:
qtranslate menu items translation