Woocommerce: cómo añadir NIF a pedidos y facturas [2017] (RESUELTO)

Añadir NIF a pedidos y facturas WooCommerce

En España es necesario incluir el NIF o DNI en la factura realizada a un particular para que dicha factura sea válida. WooCommerce, el plugin que amplía la funcionalidad de WordPress para incluir una tienda online no contempla este dato por defecto.

Woocommerce también tiene otra deficiencia, y es que no dispone de la funcionalidad de generación de facturas automáticas en su núcleo.

Vamos a solucionar ambos aspectos. Para ello instala y activa estos tres plugins

1. Woocommerce Checkout manager
2. Woocommerce PDF Invoices & Packing Slips
3. WooCommerce Store Toolkit

Configurar Woocommerce Checkout Manager para añadir el NIF/CIF

Vamos a usar este plugin para añadir el campo CIF/NIF a nuestros datos de facturación (billing). Para ello vamos a las opciones del plugin (/wp-admin/admin.php?page=woocommerce-checkout-manager) y en la pestaña Billing, añadimos el nuevo campo. Quedará algo asi:

añadir nif a facturas woocommerce

A partir de este momento, el sistema pedirá al cliente que inserte su CIF/NIF en el proceso de compra.

Configurar Woocommerce PDF para añadir el NIF/CIF

El siguiente paso es configurar este plugin para que nos permita emitir facturas en pdf, enviárselas al cliente y además refleje el nuevo campo NIF/CIF que hemos creado en el paso anterior.

El primer paso consiste en copiar las plantillas del plugin a nuestro theme para crear plantillas custom. De esta forma podremos crear unas plantillas para facturas a medida y no perderlas al actualizar el plugin. Para ello copiamos /wp-content/plugins/woocommerce-pdf-invoices-packing-slips/templates/pdf/Simple a nuestro theme /wp-content/themes/MY_THEME/woocommerce/pdf/FacturaConCIF

woocommerce factura pdf con cif

Después personalizaremos nuestro archivo invoice.php (el que genera la factura en PDF) para mostrar el nuevo campo CIF/NIF.

Para averiguar cómo se llama el nuevo campo, podemos instalar y activar WooCommerce Store Toolkit y de esta forma, en la pantalla del pedido, veremos al final todas las variables personalizadas y sus valores. Algo asi:

En mi caso el campo (cuya abreviatura era myfield12) se puede recuperar con el id _billing_myfield12

Por tanto vamos a personalizar la plantilla haciendo que salga este campo también, añadiendo la siguiente línea:

 <br /><?php $wpo_wcpdf->custom_field('_billing_myfield12', 'NIF/CIF:'); ?>

El archivo /wp-content/themes/MY_THEME/woocommerce/pdf/FacturaConCIF/invoice.php, que quedará asi:

El último paso es indicarle al plugin que use nuestra plantilla custom. Para ello vamos a Woocommerce > Facturas PDF o ruta /wp-admin/admin.php?page=wpo_wcpdf_options_page&tab=template y en el desplegable, elegimos nuestra plantilla FacturaConCIF:
cif en facturas woocommerce

¡Listo!

WooCommerce: Mostrar solo envío gratuito si está disponible

En Woocommerce 2.6 ha habido cambios importantes en la parte de los Envíos. Si tenías una versión anterior, verás que al acceder a la configuración de envíos, aparecen “Tarifa plana (heredado)” y “Envío gratuito (heredado)”. Hay que definir los nuevos métodos de envío mediante las “Shipping zones”. Lo explican muy bien aqui: http://www.tiendaonlinemurcia.es/woocommerce-versiones-novedades/

Imagina que configuras un envío gratuito para pedidos de > 120€ y una tarifa plana de 5€ para el resto de envíos. Entonces, verás que el cliente puede elegir el método de envío gratuito y el envío de 5€. Realmente solo debería aparecer el envío gratuito, porque el cliente tiene derecho a él, y no el envío por tarifa estándar, que puede dar lugar a confusión.

¿Cómo se consigue ésto? Muy fácil,

Primero borra las cachés de WooCommerce: WooCommerce > System Status > Tools > WC Transients > Clear transients.

Y después mete estas líneas al final del archivo functions.php de tu theme:

/**
 * Hide shipping rates when free shipping is available.
 * Updated to support WooCommerce 2.6 Shipping Zones.
 *
 * @param array $rates Array of rates found for the package.
 * @return array
 */
function my_hide_shipping_when_free_is_available( $rates ) {
	$free = array();
	foreach ( $rates as $rate_id => $rate ) {
		if ( 'free_shipping' === $rate->method_id ) {
			$free[ $rate_id ] = $rate;
			break;
		}
	}
	return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );

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!

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

Display qTranslate flags (language switcher) in your wordpress theme [SOLVED]

How to display a language switcher in your wordpress theme? Easy!

Edit your template file, for instance, header.php and include the following lines:

<!-- alternador de idiomas qTranslate --->
<?php if (function_exists('qtrans_generateLanguageSelectCode')) { echo qtrans_generateLanguageSelectCode('image'); } ?>

qTranslate and wordpress 3.7 [SOLVED]

If you want to migrate to new wordpress version (3.7) and are using qTranslate, make the following change to /wp-content/plugins/qtranslate/qtranslate.php before updating wordpress to the newer version!!

QT_SUPPORTED_WP_VERSION must be 3.7 as in:

define('QT_SUPPORTED_WP_VERSION', '3.7');

If you do it BEFORE UPDATING, your life will be easier. If you don’t, the plugin will auto-disable and you’ll face some issues…

Redirect wordpress main page to category [SOLVED]

This is a usual question in forums: How to redirect the wordpress main page to a category post page?

This is: when http://yoursite.com loads, you want to be redirected to http://yoursite.com/category/mycategory.

To achieve this, you can do it several ways.

Redirect wordpress main page to category using .htaccess file

Edit your .htaccess file (in your WP root folder) and replace these lines:

# BEGIN WordPress

RewriteEngine On
RewriteBase /

With these ones:

# BEGIN WordPress

RewriteEngine On
RewriteBase /

#REDIRECT HOME PAGE TO CATEGORY 'MYCATEGORY'
RewriteRule ^$ /category/mycategory [R=301,L]

Redirect wordpress main page to category in your theme

edit your theme’s index.php and insert these lines at the begining of the file:

<!-- redirect to category 'mycategory' -->
<?php
if(is_home()){
echo '<meta http-equiv="refresh" content="0; url=http://yoursite.com/category/mycategory">';
}
?>
<!-- /redirect -->

Done! 🙂

PS:
If you want to REMOVE the /category/ from the URL’s so that your categories won’t load in /category/mycategory but in /mycategory instead, read this post 😉

WordPress: smooth slider and qTranslate [solved]

WordPress extension Smooth Slider is a great choice for implementing a post+thumbnail slider in your site.

However, by default it does not work with qTranslate.

If you want smooth slider to show the post in several languages (the ones you defined used qTranslate), edit /wp-content/plugins/smooth-slider/slider_versions/j.php.

Change from (around line 50):

$rs_post = $wpdb->get_results("SELECT * FROM $posts_table WHERE ID = $id", OBJECT);
$data = $rs_post[0];
$post_title = stripslashes($data->post_title);
$post_title = str_replace('"', '', $post_title);
$slider_content = $data->post_content;

To:

$rs_post = $wpdb->get_results("SELECT * FROM $posts_table WHERE ID = $id", OBJECT);
$data = $rs_post[0];
 
// make multilang titles with qtranslate
$post_title = stripslashes(qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($data->post_title));
$post_title = str_replace('"', '', $post_title);
// make multilang excerpts(contents) with qtranslate
$slider_content = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($data->post_content);

And if your permalinks are not working, use the qtrans_convertURL($permalink) to convert permalinks too.