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…

Drupal 7: crear un módulo que consulte base de datos externa [RESUELTO]

Imaginemos que queremos leer información de una base de datos externa en Drupal 7. Para ello vamos a crear un módulo. El tutorial cubrirá el proceso completo desde la instalación de Drupal.

Consideraciones iniciales

Todo el ejemplo se hará en entorno MAMP versión 2.2 sobre OS X.

Apache:
La carpeta de trabajo será el htdocs de Apache en el path: /Applications/MAMP/htdocs
Apache estará corriendo en puerto 80
La versión de PHP utilizada es PHP 5.5.3 (¡con todas las caches -tipo APC- desactivadas!)

Base de datos:
Elegiremos MySQL, que escuchará en el puerto 3306
El usuario con que conectaremos a MySQL será root y su password será root (recuerda no hacer esto NUNCA en un entorno de producción). La base de datos que usaremos para la prueba se llamará drupal y el usuario root tendrá todos los permisos sobre ella.

Variables de entorno
Vamos a añadir al $PATH el path donde tenemos los binarios de MySQL (por defecto en /Applications/MAMP/Library/bin) para poder realizar llamadas a los binarios desde línea de comandos de forma más cómoda. Lo podemos hacer mediante la orden:

miguelm$ export PATH=$PATH:/Applications/MAMP/Library/bin

Drupal:
La realease empleada será Drupal 7.21

Paso 1: Instalación de Drupal

– Descomprimir el zip en /Applications/MAMP/htdocs

– Crear la nueva base de datos para Drupal:

miguelm$ mysqladmin -u root -p create drupal
Enter password:

– Entrar a MySQL:

miguelm$ mysql -u root -p

– Dar permisos al usuario root para usar esa BD:

mysql> GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER
    ->   ON drupal.*
    ->   TO 'root'@'localhost' IDENTIFIED BY 'root';
Query OK, 0 rows affected (0,06 sec)

– Configurar Drupal para la instalación.
Primero nos movemos al directorio donde hemos descomprimido el zip de Drupal…

miguelm$ cd /Applications/MAMP/htdocs/

Y editar el fichero settings.php para decirle cómo se llama nuestra base de datos, nuestro usuario y demás…

miguelm$ vim ./sites/default/settings.php

La configuración de las bases de datos tiene que quedar asi:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

En entornos de desarrollo también es muy interesante incluir estas líneas en el archivo settings.php, para que se muestren en web los errores de PHP:

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

El siguiente paso es instalar Drupal. Para ello, abrimos el navegador y (teniendo Apache levantado) procedemos a ejecutar install.php visitando la URL: http://localhost/install.php

instalacion de drupal7

Haremos una instalación estándar en idioma inglés. El instalador debe terminar y veremos esta pantalla.

tutodrup2

Entonces nos loggeamos en nuestro recién creado site visitando la URL: http://localhost/?q=user y rellenando el username y pwd con los valores elegidos (por ejemplo, admin/admin)

Paso 2: Creación de base de datos externa

Ya tenemos Drupal instalado. Vamos ahora a crear una base de datos de prueba con una única tabla muy sencilla, que almacene por ejemplo una relación de títulos de libros.

Creamos la nueva bd, a la que llamaremos externaldatabase.

miguelm$ mysqladmin -u root -p create externaldatabase

A continuación entramos en MySQL para asignar privilegios (lo haremos con el usuario root, aunque recordemos que en entornos de producción elegiríamos otro user para esta bd)

mysql> GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER on externaldatabase.* TO 'root'@'localhost' IDENTIFIED BY 'root';
Query OK, 0 rows affected (0,02 sec)

Y creamos nuestra tabla con datos de libros:

mysql> USE externaldatabase;
Database changed
mysql> CREATE TABLE libros (id INT, titulo VARCHAR(200));
Query OK, 0 rows affected (0,04 sec)

Insertamos un par de datos de prueba:

mysql> INSERT into libros (id, titulo) VALUES (1,"El Quijote");
Query OK, 1 row affected (0,03 sec)

Paso 3: Nuevo módulo en Drupal 7:

Los módulos en Drupal están (normalmente) en /sites/all/modules
Vamos a crear una nueva carpeta en ese path que se llamará bdexterna.

miguelm$ pwd
/Applications/MAMP/htdocs
miguelm$ cd sites/all/modules/
miguelm$ mkdir bdexterna

Un módulo se compone de dos archivos: un archivo con extensión .info (definición del módulo) y un archivo con extensión .module (que contiene la lógica -programación PHP-).

Vamos a crear nuestro archivo externaldbtest.info dentro de la carpeta externaldbtest:

miguelm$ cd bdexterna
miguelm$ vim bdexterna.info

El contenido de externaldbtest/externaldbtest.info será:

name = BD Externa
description = "Modulo para consultar BD externa"
package = Aprendiendo Drupal7 en leccionespracticas.com
core = 7.x

También creamos el archivo bdexterna.module que, de momento, dejamos vacío…:

miguelm$ touch bdexterna.module

Esto quiere decir que el módulo se llamará BD Externa, que se ubicará en la categoría de módulos “Aprendiendo Drupal7”, es compatible con Drupal 7.x y también describimos para qué sirve.

Una vez creados estos archivo podemos ir a http://localhost/?q=user/1#overlay=%3Fq%3Dadmin%252Fmodules en nuestro navegador y veremos que se ha creado una nueva categoría llamada “Aprendiendo Drupal7 en leccionespracticas.com” que contiene el módulo “BD Externa” (y se nos permite activarlo):

conexion a base de datos externa drupal con un nuevo módulo

Antes de lanzarnos a hacer queries a nuestra base de datos externa, debemos entender cómo funcionan los módulos de Drupal. Y para ello nada mejor que empezar con un “Hola Mundo!”. Vamos a generar un bdexterna.module de tal forma que al visitar la url http://localhost/?q=libros/listar nos diga “Hola mundo”.

Para programar la respuesta a una determinada URL (/libros/listar) debemos usar la función hook_menu(). Al visitar una URL, Drupal comprueba si alguno de nuestros módulos tiene programado una función nombremodulo_menu() para esta dirección.

Vamos a empezar, por tanto, creando esta función.

saludar/saludar.module

<?php
/**
 * @file
 * Nuestro primer módulo en Drupal (leccionespracticas.com)
 */
 
/**
 * Implementa hook_menu().
 */
function bdexterna_menu() {
  $items['libros/listar'] = array(
    'title' => 'LISTAR LIBROS',
    'page callback' => 'bdexterna_libros_listar',
    'access callback' => TRUE,
  );
  // con lo anterior indicamos que cuando se visite la url libros/listar
  // se muestre una página con título 'LISTAR LIBROS' cuya salida será el
  // resultado de ejecutar la funcion 'bdexterna_libros_listar', que deberemos definir...
 
  return $items;
} 
?>

Y además deberemos crear la función de callback que hemos dicho que debía ejecutarse al visitar esta url, que será muy simple porque solo queremos mostrar un “Hola Mundo!”. Recordamos que el nombre que debemos darle a esta función es el que indicamos en el parámetro page_callback, osea bdexterna_libros_listar.

/**
 * Callback para libros/listar.
 */
function bdexterna_libros_listar() {
  return "Hola Mundo";
}

La primera versión completa de nuestro archivo bdexterna.module será, por tanto, asi:

<?php
/**
 * @file
 * Nuestro primer módulo en Drupal (leccionespracticas.com)
 */
 
/**
 * Implementa hook_menu().
 */
function bdexterna_menu() {
  $items['libros/listar'] = array(
    'title' => 'LISTAR LIBROS',
    'page callback' => 'bdexterna_libros_listar',
    'access callback' => TRUE,
  );
  // con lo anterior indicamos que cuando se visite la url libros/listar
  // se muestre una página con título 'LISTAR LIBROS' cuya salida será el
  // resultado de ejecutar la funcion 'bdexterna_listar_libros', que 
  // deberemos definir
  // el parámetro access callback indica quién puede acceder al callback:
  // en este caso, al tener el valor TRUE, todos pueden acceder.
 
  return $items;
} 
 
/**
 * Callback para URL libros/listar
 */
function bdexterna_libros_listar() {
  return "Hola Mundo";
}

Solo nos queda activar el módulo, vaciar las caches de Drupal (URL http://localhost/?q=admin/config/development/performance) y visitar la URL elegida (http://localhost/?q=libros/listar). Comprobamos que se ve el “Hola Mundo”.

Drupal hola mundo menu_hook

Función (callback) para consulta a base de datos

Ahora que hemos entendido cómo funcionan los hooks y hemos construído un módulo básico, podemos lanzarnos a conseguir nuestro objetivo: listar los libros.

Para ello modificaremos la función de callback que habíamos definido en el archivo bdexterna.module (llamada bdexterna_libros_listar) y añadiremos el código necesario para realizar la consulta a la BD externa de libros.

Lo primero que debemos hacer es definir la nueva base de datos externa en Drupal. Como vimos en el post anterior, podemos hacerlo de dos formas. En este caso y puesto que solo usaré esta base de datos desde este módulo, optaré por definir la base de datos directamente en el propio módulo.

El código es bastante sencillo y self-explaining:

/**
 * Callback para libros/listar.
 */
function bdexterna_libros_listar() {
  // Definimos la base de datos externa...
 
  $bd_libros = array(
    'database' => 'externaldatabase', // nombre de la BD externa
    'username' => 'root',             // usuario para acceder a la BD externa
    'password' => 'root',             // password del usuario
    'host' => 'localhost',            // host donde se encuentra la BD
    'driver' => 'mysql',              // tipo de BD
  );

A continuación introducimos el código para limpiar las caches. Este paso es vital. De no hacerlo, podríamos encontrarnos con que Drupal intenta acceder a tablas de la nueva base de datos que no existen (semaphore, session, etc etc) y nos encontraríamos con errores del tipo:

Uncaught exception thrown in shutdown function.
 
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;externaldatabase.semaphore&#039; doesn&#039;t exist: ...

Y si no me creéis, mirad:
drupal external database semaphore error

El código que limpia las caches es el siguiente (lo he cogido prestado de aqui).

  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  foreach ($cache_tables as $table) {
   cache_clear_all('*', $table, TRUE);
  }

A continuación añadimos la BD definida anteriormente y la marcamos como BD activa:

Database::addConnectionInfo('externaldatabase', 'default', $bd_libros);
  // 'MisLibros' es una clave única de la BD en este módulo, default es el target y $other_database el vector que contiene la información de conexión
 
  db_set_active('externaldatabase');
  // marcamos la bd activa como la externa...

Y podemos empezar a construir queries y mostrar resultados…

// y empezamos a construir la query..
  $sql = "SELECT * from libros";
 
  //print "Vamos a ejecutar la consulta '".$sql."'...<br />";
 
  // lanzamos la ejecución de la query y guardamos en $result todos los resultados...
  $results = db_query($sql);
 
  // mostramos los resultados...
  foreach($results as $res){
    print_r($res);
  }

Y lo único que restaría sería restaurar la BD por defecto:

// restaurar la BD activa a la Bd de Drupal...
  db_set_active();

El fichero bdexterna.module completo quedaría asi:

bdexterna.module

<?php
 
/**
 * @file
 * Nuestro primer módulo en Drupal (leccionespracticas.com)
 */
 
/**
 * Implementa hook_menu().
 */
function bdexterna_menu() {
  $items['libros/listar'] = array(
    'title' => 'LISTAR LIBROS',
    'page callback' => 'bdexterna_libros_listar',
    'access callback' => TRUE,
  );
  // con lo anterior indicamos que cuando se visite la url libros/listar
  // se muestre una página con título 'LISTAR LIBROS' cuya salida será el
  // resultado de ejecutar la funcion 'bdexterna_listar_libros', que deberemos definir
 
  return $items;
}
 
 
function bdexterna_clear_cache() {
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  foreach ($cache_tables as $table) {
   cache_clear_all('*', $table, TRUE);
  }
}
 
/**
 * Callback para libros/listar.
 */
function bdexterna_libros_listar() {
 
  bdexterna_clear_cache();
  db_set_active();
 
  // Definimos la base de datos externa...
  $bd_libros = array(
    'database' => 'externaldatabase', // nombre de la BD externa
    'username' => 'root',             // usuario para acceder a la BD externa
    'password' => 'root',             // password del usuario
    'host' => 'localhost',            // host donde se encuentra la BD
    'driver' => 'mysql',              // tipo de BD
  );
 
  Database::addConnectionInfo('externaldatabase', 'default', $bd_libros);
  // 'MisLibros' es una clave única de la BD en este módulo, default es el target y $other_database el vector que contiene la información de conexión
 
  db_set_active('externaldatabase');
  // marcamos la bd activa como la externa...
 
  // y empezamos a construir la query..
  $sql = "SELECT * from libros";
 
  // lanzamos la ejecución de la query y guardamos en $result todos los resultados...
  $results = db_query($sql);
 
  // mostramos los resultados...
  foreach($results as $res){
    print_r($res);
  }  
 
  // restaurar la BD activa a la Bd de Drupal...
  db_set_active();
 
  //informar del final del proceso
  drupal_set_message(t('The queries have been made.'));
}
 
?>

Y el resultado:
tutodrup10

Nótese que el resultado sale “feo” porque hacemos print’s desde el módulo. Lo que deberíamos hacer es RETURN’s de HTML (ver el siguiente punto).

El código final del módulo

He comprobado que algunas cosas de las enunciadas en apartados anteriores no son del todo ciertas. Por ejemplo, no es necesario el tema de vaciar las caches. También es interesante capturar en bloques try/except algunas cosas. Y por supuesto, no realizar presentación desde la capa de lógica (es decir, devolver cadenas HTML, no hacer prints desde el módulo…)

Esta versión del código contempla estas modificaciones.

bdexterna.info:

name = BD Externa
description = "Modulo para consultar BD externa"
package = Aprendiendo Drupal7 en leccionespracticas.com
core = 7.x

bdexterna.module:

<?php
 
/**
 * @file
 * Nuestro primer módulo en Drupal (leccionespracticas.com)
 */
 
/**
 * Implementa hook_menu().
 */
function bdexterna_menu() {
  $items['libros/listar'] = array(
    'title' => 'LISTAR LIBROS',
    'page callback' => 'bdexterna_libros_listar',
    'access callback' => TRUE,
  );
  // con lo anterior indicamos que cuando se visite la url libros/listar
  // se muestre una página con título 'LISTAR LIBROS' cuya salida será el
  // resultado de ejecutar la funcion 'bdexterna_listar_libros', que deberemos definir
 
  return $items;
}
 
/**
 * Callback para libros/listar.
 */
function bdexterna_libros_listar() {
 
  $bd_libros = array(
    'database' => 'externaldatabase', // nombre de la BD externa
    'username' => 'root',             // usuario para acceder a la BD externa
    'password' => 'root',             // password del usuario
    'host' => 'localhost',            // host donde se encuentra la BD
    'driver' => 'mysql',              // tipo de BD
  );
 
  try{
  	  Database::addConnectionInfo('externaldatabase', 'default', $bd_libros);
     db_set_active('externaldatabase');
  } 
  catch (Exception $e){
  	  db_set_active();
     return "se produjo un error al marcar la BD activa: ".$e;  
  }
  $sql = "SELECT * from libros";
  $results = db_query($sql);
  $salida = "";  
  foreach($results as $res){
    $salida = $salida."[ID] =".$res->id."  [TITULO] = ".$res->titulo;
  }  
  db_set_active();
  return $salida;
}
?>

Y la salida que conseguiremos:
drupal consulta base de datos externa resuelto

Drupal 7: acceso a bases de datos externas

En Drupal 7 hay varias formas de acceder a bases de datos externas.

Método 1: Añadir bases de datos adicionales en la configuración (settings.php)

<?php
$databases = array();
$databases['default']['default'] = array(
  // Drupal's default credentials here.
  // This is where the Drupal core will store it's data.
);
$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.
);
?>

Y asi es como realizaríamos el cambio de base de datos activa en el módulo…

<?php
// Use the database we set up earlier
db_set_active('my_other_db');
 
// Run some queries, process some data
// ...
 
// Go back to the default database,
// otherwise Drupal will not be able to access it's own data later on.
db_set_active();
?>

Método 2: definir las bases de datos adicionales “al vuelo” en el propio módulo

Esta forma es la más adecuada si las queries a la base de datos secundaria provienen únicamente de un módulo.

Puedes leer la información de la capa de abstracción para bases de datos de drupal aqui: http://api.drupal.org/api/drupal/includes%21database%21database.inc/group/database/7

<?php
  $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');
 
  // execute queries here
 
  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));
?>

[SOLVED] Fix apple-touch-icon 404 errors

Some days ago I was checking AWStats reports in my Invenio site and I noticed some (unexpected) 404 errors. Visitors were trying to load URL’s like /iphone or /m and some images which were not linked in my site… (‘apple-touch-icon.png‘ and similar filenames).

apple-touch-icon-precomponsed.png 404 fix

This has to do with some bots coming along, assuming that my site includes a mobile version, and then trying its hand at guessing the location. In the common request-set listed above, we see the bot looking first for an “apple-touch icon,” and then for mobile content in various directories.

But what about thoses images? Take a read at: http://www.computerhope.com/jargon/a/appletou.htm

Similar to the Favicon, the apple-touch-icon.png is a file used for a web page icon on the Apple iPhone, iPod Touch, and iPad. When someone bookmarks your web page or adds your web page to their home screen this icon is used. If this file is not found these Apple products will use the screen shot of the web page, which often looks like no more than a white square.

This file should be saved as a .png, have dimensions of 57 x 57, and be stored in your home directory, unless the path is specified in the HTML using the below code.

When this file is used, by default, the Apple product will automatically give the icon rounded edges and a button-like appearance.

I wanted to fix this, so I began by testing if mod_rewrite was enabled…

[root@aneto www]# grep -R "mod_rewrite" /etc/httpd/conf/
/etc/httpd/conf/httpd.conf:LoadModule rewrite_module modules/mod_rewrite.so

The LoadModule line is uncommented, so it is enabled.

Next step would be to try a basic redirection to test mod_rewrite.

Edit $PATH_TO_INVENIO/etc/apache/invenio-apache-vhost.conf and added this lines in the VirtualHost part.

<ifmodule mod_rewrite.c>
           RewriteEngine  On
           RewriteLog "/home/apache/rewrite.log"
           RewriteLogLevel 9
           RewriteRule old.html bar.html [R]
</ifmodule>

Then restart apache…

[root@aneto ~]# /etc/init.d/httpd  restart

Then open your browser and test the redirection. You should be redirected and the /home/apache/rewrite.log should log that redirection…

[root@aneto ~]# tail -n20 -f /home/apache/rewrite.log
 
155.210.47.93 - - [05/Jul/2013:12:21:06 +0200] [155.210.47.102/sid#2b689442f0c8][rid#2b68947a7380/initial] (2) init rewrite engine with requested uri /old.html
155.210.47.93 - - [05/Jul/2013:12:21:06 +0200] [155.210.47.102/sid#2b689442f0c8][rid#2b68947a7380/initial] (3) applying pattern 'old.html' to uri '/old.html'
155.210.47.93 - - [05/Jul/2013:12:21:06 +0200] [155.210.47.102/sid#2b689442f0c8][rid#2b68947a7380/initial] (2) rewrite '/old.html' -> 'bar.html'
155.210.47.93 - - [05/Jul/2013:12:21:06 +0200] [155.210.47.102/sid#2b689442f0c8][rid#2b68947a7380/initial] (2) explicitly forcing redirect with http://155.210.47.102/bar.html
155.210.47.93 - - [05/Jul/2013:12:21:06 +0200] [155.210.47.102/sid#2b689442f0c8][rid#2b68947a7380/initial] (1) escaping http://155.210.47.102/bar.html for redirect
155.210.47.93 - - [05/Jul/2013:12:21:06 +0200] [155.210.47.102/sid#2b689442f0c8][rid#2b68947a7380/initial] (1) redirect to http://155.210.47.102/bar.html [REDIRECT/302]
155.210.47.93 - - [05/Jul/2013:12:21:06 +0200] [155.210.47.102/sid#2b46e1df80d8][rid#2b46eac962e0/initial] (2) init rewrite engine with requested uri /bar.html
155.210.47.93 - - [05/Jul/2013:12:21:06 +0200] [155.210.47.102/sid#2b46e1df80d8][rid#2b46eac962e0/initial] (3) applying pattern 'old.html' to uri '/bar.html'
155.210.47.93 - - [05/Jul/2013:12:21:06 +0200] [155.210.47.102/sid#2b46e1df80d8][rid#2b46eac962e0/initial] (1) pass through /bar.html

Now that we know that mod_rewrite is working properly, lets add some code to forbid some URL patterns (more refences)…

<ifmodule mod_rewrite.c>
           RewriteEngine  On
           RewriteLog "/home/apache/rewrite.log"
           RewriteLogLevel 9
           #RewriteRule old.html bar.html [R]
           RewriteCond %{REQUEST_URI} /iphone/?$ [NC,OR]
           RewriteCond %{REQUEST_URI} /mobile/?$ [NC,OR]
           RewriteCond %{REQUEST_URI} /mobi/?$ [NC,OR]
           RewriteCond %{REQUEST_URI} /m/?$ [NC]
           RewriteRule (.*) - [F,L]
</ifmodule>

This technique is useful for saving bandwidth and server resources, not just for non-existent mobile-ish requests, but also for any resource that you would like to block – just add a RewriteCond with the target character string of your choice. Hopefully this technique will help you run a cleaner, safer, and more secure website.

Now, what to do with those apple-touch-icon-precomposed.png and similar images which are ending in 404 errors?

First read full Apple documentation about this issue.

Then you can fix it several ways:

1) Search for those images and download them to /soft/cds-invenio/var/www/

cd /soft/cds-invenio/var/www/
wget http://gwt-touch.googlecode.com/svn-history/r86/trunk/demo-ipad-settings/war/apple-touch-icon-precomposed.png

Or you can create some personalized images using online services like http://iconifier.net/

Captura de pantalla 2013-07-05 a la(s) 14.32.55

And you’re ready to go! Logs won’t show those ugly 404 errors from now on and visitors using iphone’s will be happier 🙂

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 😉

Drupal 7: install module translation [SOLVED]

To install a Drupal 7 module translation, this is, a .po file (for instance, the fullcalendar spanish translation) go to Administration » Configuration » Regional and language (/admin/config/regional/translate).

Click the ‘Import’ tab and use the ‘Import translation’ form.

drupl

What if there are still some strings translations missing? No worries, just go to /admin/config/regional/translate/translate and add them (by hand).

Tip: use Localization update module 😉

Drupal 7: display language switcher in template [SOLVED]

Some days ago we learnt to display a search box in Drupal template files, and according to that post and the Drupal handbook rendering a language switcher block in your theme templates should be easy.

This should work:

<?php
$block = module_invoke('locale', 'block_view', 'language');
print render($block);
?>

Unfortunately, in my D7 it does not. What does work is this:

Add to template.php:

<?php
function block_render($module, $block_id) {
  $block = block_load($module, $block_id);
  $block_content = _block_render_blocks(array($block));
  $build = _block_get_renderable_array($block_content);
  $block_rendered = drupal_render($build);
  return $block_rendered;
}
?>

Add to page.tpl.php

<?php
  print block_render('locale', 'language');
?>

Now that the language switcher is rendering, you might want to customize its appeareance 😉

Drupal 7: Styling language switcher

Language switcher is a Drupal module which allows to display a block that allows visitors to choose between the languages in which your site is available (check /admin/config/regional/language to list the available languages in your Drupal site).

By default, it produces an unordered list with each item in a new line and a bullet before each item. Not a big fan of this look.

With the following CSS code you’ll have an inline language switcher, with li items separed by “/”.

/* language switcher */
ul.language-switcher-locale-url{
list-style: none;
display: inline;
}
 
ul.language-switcher-locale-url li{
display: inline;
}
 
ul.language-switcher-locale-url li:after{
   content: "/";
}
 
ul.language-switcher-locale-url li:last-child:after{
   content: "";
}

For more advanced styling options, check this link.

Drupal 7: Path breadcrumbs in Views page [SOLVED]

Path breadcrumbs module allows you to easily add breadcrumbs to your Drupal site. The module lacks of documentation, but they offer this image as an example:

path_breadcrumbs

And there is a videotutorial as well.

The above show how to configure breadcrumbs in nodes, but… how to display breadcrumbs in Views pages?

This struggled me for a while, because I was taking the (limited) instructions too literally.

To create a breadcrumb to a views page display that has a path like “/path/to/my-view” just use that as the path (as it isn’t an alias). To know the path, go to your view and edit it (admin/structure/views/view/VIEWNAME/edit) and refer to the Page Settings – Path value.

Also, leave the “Arguments” and “Selection rules” empty, then setup your breadcrumbs as you did with nodes.

Let’s see an example. First, the path to the view:

Path breadcrumbs in views

Path breadcrumbs in views

And the path breadcrumbs configuration:

drupal 7 Path breadcrumbs in views

drupal 7 Path breadcrumbs in views

And here is the resulting breadcrumb. Remember that your theme’s page.tpl.php must print $breadcrumb or you will not see breadcrumbs at all…

path_breadcrumbs_in_views_page_2