Español
Creando un theme para WP Carousel
Partiremos de un archivo index.php que almacenará la información del theme, cosas como nombre del autor, versión, descripción y archivos CSS que usará (no se permiten añadir archivos Javascript), en una matriz llamada $theme. A continuación podéis ver el código del archivo index.php del theme Default:
// THEME INFORMATION
$theme['author'] = "Sumolari";
$theme['author_url']= "http://sumolari.com";
$theme['name'] = "WP Carousel 0.3 Look";
$theme['url'] = "http://sumolari.com/wp-carousel";
$theme['desc'] = __('Use WP Carousel 0.3\'s theme', 'wp_carousel');
$theme['version'] = '1.0';
$theme['css'] = array();
$theme['css'][] = 'style.css';
?>
Otro archivo fundamental en los themes es el archivo theme.php, que mostrará el contenido del carrusel. Lo cierto es que en este punto los themes no son muy flexibles: tienen que tener una estructura bastante fija en el diseño. A continuación podéis ver el código mínimo de un theme de WP Carousel comentado y explicado.
echo '
<div class="nombre_de_mi_theme">'; // Es recomendable poner al principio una capa que tenga por clase el nombre del theme, así se evitan conflictos relacionados con el CSS de otros themes que estén activados en otros carruseles
if ($config['ARROWS']): // Comprobamos si están habilitadas las flechas y en cada desplazamiento manual se debe desplazar como mínimo un panel
echo '<a href="javascript:stepcarousel.stepBy(\'carousel_'.$c_id.'\', '.$config['SLIDE_POSTS'].')">'; // Enlace para adelantar un panel
printf(__('Forward %s panel', 'wp_carousel'), $config['SLIDE_POSTS']); // Texto del enlace
echo '</a>'; // Fin del enlace
endif; // Fin de la comprobación
if ($config['ARROWS']): // Comprobamos si están habilitadas las flechas y en cada desplazamiento manual se debe desplazar como mínimo un panel
echo '<a href="javascript:stepcarousel.stepBy(\'carousel_'.$c_id.'\', -'.$config['SLIDE_POSTS'].')">'; // Enlace para retroceder un panel
printf(__('Back %s panel', 'wp_carousel'), $config['SLIDE_POSTS']); // Texto del enlace
echo '</a>'; // Fin del enlace
endif; // Fin de la comprobación
?>
<div id="carousel_<?php echo $c_id; ?>" class="stepcarousel">
<div class="belt">
$item): // Iniciamos el bucle que mostrará los elementos del carrusel, donde $i_id es la ID INTERNA de los elementos del carrusel (la ID que utiliza WP Carousel) y el índice ID de la matriz $item es la ID que tiene el elemento dentro de WordPress. En este ejemplo están todos los índices importantes de $item, hay más, pero no merecen ser explicados ya que no son usados mas que internamente por WP Carousel ?>
<div class="panel">>
<a title="<?php echo $item['TITLE']; ?>" href="<?php echo $item['LINK_URL']; ?>">
<img title="<?php echo $item['TITLE']; ?>" src="<?php echo $item['IMAGE_URL']; ?>" alt="<?php echo $item['TITLE']; ?>" width="<?php if ($config['HAS_IMG_WIDTH']) { echo $config['IMG_WIDTH']; } else { echo '100px'; } ?>" height="<?php if ($config['HAS_IMG_HEIGHT']) { echo $config['IMG_HEIGHT']; } else { echo '100px'; } ?>" />
</a>
<div class="panel-text">
</div>
</div>
</div>
</div>
<div id="carousel_<?php echo $c_id; ?>-paginate" class="wp_carousel_default_pagination">
<img src="<?php echo $path[6]; ?>/img/opencircle.png" alt="" /></div>
endif;
echo '</div>
'; // Cerramos la capa con la clase especial para evitar conflictos CSS
?>
Con esto ya tenemos dos tercios del trabajo hecho, pero nos queda el CSS, que también es algo restrictivo, ya que tenemos que partir de un código CSS básico que es:
.nombre_de_mi_theme .stepcarousel {
position: relative;
overflow: scroll;
}
.nombre_de_mi_theme .stepcarousel .belt {
position: absolute;
left: 0;
top: 0;
}
.nombre_de_mi_theme .stepcarousel .panel {
float: left;
overflow: hidden;
}
Os recomiendo que diseñéis teniendo en cuenta que hay otros themes y que puede que haya dos themes en uso a la vez, así que hay que procurar una máxima compatibilidad entre los themes.
Integrando WP Carousel en nuestros themes
Desde la versión 0.4 de WP Carousel, los carruseles admiten themes, y claro, esto da mucho juego a los diseñadores, que con un poco de ingenio y creatividad, pueden hacer maravillas. También permite darle al carrusel un toque más acorde con el diseño de nuestros blogs, aunque claro, es posible que al distribuir nuestro theme con soporte de WP Carousel muchos usuarios se pierdan a la hora de instalar un segundo theme para WP Carousel.
Sin embargo, en la versión 0.4.0.1 añadí un parámetro muy útil a la función wp_carousel() (encargada de mostrar el carrusel): el parámetro $mode. Este parámetro acepta tres valores: show, get y array. El primero es que se toma por defecto y muestra el carrusel. El segundo devuelve el código HTML generado por el theme, mientras que el tercero devuelve una matriz con el contenido y la configuración del carrusel. Entonces disponemos de dos métodos diferentes para integrar WP Carousel en nuestro theme: llamándolo estableciendo el parámetro $mode en get (y reemplazando código) o llamándolo estableciendo el parámetro $mode en array, para más adelante crear un theme muy similar a los normales de WP Carousel, sólo que almacenado en la carpeta de nuestro theme e inseleccionable desde la página de opciones de WP Carousel.
Veamos cómo hacerlo.
Lo primero que haremos será crear una variable que almacene la matriz que devuelve wp_carousel() con el parámetro $mode establecido en array. Podemos crearla dentro de una función, en el archivo functions.php o directamente en el archivo correspondiente de nuestro theme (header.php, index.php, etc).
A continuación cargamos en nuevas variables la configuración del carrusel y sus elementos. La matriz que hemos obtenido antes tiene 3 índices: CONFIG, que almacena la configuración, ITEMS, que almacena los elementos e ID, que almacena la ID del carrusel (aunque ésta debemos definirla nosotros, así que no es de mucha utilidad).
He creado la variable $c_id para que el mismo código de un theme normal de WP Carousel sirva en nuestro theme especial y he tomado el valor del índice ID de la matriz del primer paso para hacer uso de éste, aunque podríamos haberlo tomado del valor que usamos como primer parámetro de la función wp_carousel().
A continuación utilizo la función eval() para crear la función encargada de cargar el código Javascript necesario para iniciar el carrusel. La siguiente línea tan sólo carga la función en el pie de página del theme.
Por último, cargamos el archivo wp-carousel-theme.php, que es el que contiene el theme en mi ejemplo. El código que podéis ver a continuación es el que utilizo para integrar WP Carousel en Portal Colorido 2.0.
$carousel_array = wp_carousel(ID_DEL_CARRUSEL, 'array');
$carousel_config = $carousel_array['CONFIG'];
$carousel_items = $carousel_array['ITEMS'];
$c_id = $carousel_array['ID'];
eval('if (!function_exists("wp_carousel_load_carousel_'.$c_id.'_js_code")) { function wp_carousel_load_carousel_'.$c_id.'_js_code() { wp_carousel_load_carousel_js('.$c_id.'); } }');
add_action('wp_footer', 'wp_carousel_load_carousel_'.$c_id.'_js_code');
require_once('wp-carousel-theme.php');
El archivo wp-carousel-theme.php contiene un theme normal de WP Carousel, la única diferencia es que la matriz $config en este caso es $carousel_config, al igual que la matriz $items es $carousel_items. Podéis seguir este tutorial para crear el theme de WP Carousel.
Como veis, no tiene demasiada complicación y no difiere demasiado del sistema general de creación de themes de WP Carousel.
Creando un extra para WP Carousel
Desde la versión 0.5, WP Carousel soporta extras. Los extras permiten ampliar el contenido que es capaz de mostrar WP Carousel. Imaginemos que lo que nos interesa es mostrar la última imagen subida a Facebook de un usuario, o el último Tweet de un compañero. La solución para hacer que este contenido se actualice automáticamente es crear un extra que lo interprete.
Los extras funcionan de forma similar a los themes, y se componen de dos archivos básicos: index.php y extra.php. El archivo index.php contiene la matriz de información acerca del extra. Es muy importante que el contenido de esta matriz sea correcto, ya que sino no funcionará el extra.
A continuación tenéis el código del archivo index.php del extra Last tweet.
// Extra information
$extra['author'] = "Sumolari";
$extra['author_url']= "http://sumolari.com";
$extra['name'] = __('Last tweet', 'wp_carousel');
$extra['url'] = "http://sumolari.com/wp-carousel";
$extra['desc'] = __('Show the lastest tweet from a Twitter user', 'wp_carousel');
$extra['version'] = '1.0';
// Functions to get item's information
$extra['image_url_function'] = 'swpc_tweet_image_url';
$extra['link_url_function'] = 'swpc_tweet_link_url';
$extra['title_function'] = 'swpc_tweet_title';
$extra['desc_function'] = 'swpc_tweet_desc';
La primera mitad de la matriz contiene información acerca del nombre y el autor del extra, así como la descripción de su uso. La segunda parte es mucho más importante, e indica el nombre de las funciones definidas en el archivo extra.php que se usarán para obtener los datos el elemento, datos como la URL de la imagen, la URL del enlace y el título y la descripción del elemento.
Estas funciones deben ser únicas, no pueden repetirse en ningún extra, así que lo mejor es usar nombres que no se vayan a repetir. Estas funciones se definen en el archivo extra.php. Todas las funciones admiten un único parámetro: $id, que se corresponde con la ID que escriba el usuario al añadir el contenido al carrusel. Es ID no tiene por qué ser numérica.
El código del archivo extra.php de Last tweet es el siguiente:
// Returns the image URL
function swpc_tweet_image_url($id)
{
$format = 'json';
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$id}.{$format}"));
return $tweet[0]->user->profile_image_url;
}
// Returns the link to the item
function swpc_tweet_link_url($id)
{
$format = 'json';
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$id}.{$format}"));
return 'http://twitter.com/'.$id.'/status/'.$tweet[0]->id;
}
// Returns the title
function swpc_tweet_title($id)
{
$format = 'json';
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$id}.{$format}"));
return $tweet[0]->user->screen_name;
}
// Returns the desc
function swpc_tweet_desc($id)
{
$format = 'json';
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$id}.{$format}"));
return $tweet[0]->text;
}
Como veis todas las funciones admiten un único parámetro y deben devolver el contenido que se requiere en cada caso.
English
Creating a WP Carousel’s theme
WP Carousel‘s theme needs two files: index.php and theme.php. index.php contains information about the theme and the theme’s author, like the version of the theme, the path to the CSS files, the author’s name… This information is stored in an array called $theme.
The following code is the WP Carousel‘s default theme’s index.php code:
// THEME INFORMATION
$theme['author'] = "Sumolari";
$theme['author_url']= "http://sumolari.com";
$theme['name'] = "WP Carousel 0.3 Look";
$theme['url'] = "http://sumolari.com/wp-carousel";
$theme['desc'] = __('Use WP Carousel 0.3\'s theme', 'wp_carousel');
$theme['version'] = '1.0';
$theme['css'] = array();
$theme['css'][] = 'style.css';
The other main file is theme.php. This file contains the theme itself. The themes must have a determined structure to work correctly. The following code is the minimum code for a WP Carousel‘s theme, commented and explained:
echo '
<div class="name_of_the_theme">'; // It's recommended to add first a div which has the theme's name as class, with that you can avoid some problems with others themes' CSS code.
if ($config['ARROWS']): // We check is arrows are enabled or not
echo '<a href="javascript:stepcarousel.stepBy(\'carousel_'.$c_id.'\', '.$config['SLIDE_POSTS'].')">'; // Link to forward a panel
printf(__('Forward %s panel', 'wp_carousel'), $config['SLIDE_POSTS']); // Link text
echo '</a>'; // End of link
endif; // End of check
if ($config['ARROWS']): // We check if arrows are enabled
echo '<a href="javascript:stepcarousel.stepBy(\'carousel_'.$c_id.'\', -'.$config['SLIDE_POSTS'].')">'; // Link to back a panel
printf(__('Back %s panel', 'wp_carousel'), $config['SLIDE_POSTS']); // Link text
echo '</a>'; // End of link
endif; // End of check
?>
<div id="carousel_<?php echo $c_id; ?>" class="stepcarousel">
<div class="belt">
$item): // We start the loop which will show the carousel's items, where $i_id is the INTERNAL ID of the item, and the index ID of the array $item is the ID of the item in WordPress. In this example are the most important indexes of the array, there are more indexes, but they're not important. ?>
<div class="panel">>
<a title="<?php echo $item['TITLE']; ?>" href="<?php echo $item['LINK_URL']; ?>">
<img title="<?php echo $item['TITLE']; ?>" src="<?php echo $item['IMAGE_URL']; ?>" alt="<?php echo $item['TITLE']; ?>" width="<?php if ($config['HAS_IMG_WIDTH']) { echo $config['IMG_WIDTH']; } else { echo '100px'; } ?>" height="<?php if ($config['HAS_IMG_HEIGHT']) { echo $config['IMG_HEIGHT']; } else { echo '100px'; } ?>" />
</a>
<div class="panel-text">
</div>
</div>
</div>
</div>
<div id="carousel_<?php echo $c_id; ?>-paginate" class="wp_carousel_default_pagination">
<img src="<?php echo $path[6]; ?>/img/opencircle.png" alt="" /></div>
endif;
echo '</div>
'; // End of our theme's div
?>
With that we have the theme’s HTML code, but we need some CSS. There’s the basic CSS for a WP Carousel theme, without this code, the carousel won’t work.
.name_of_the_theme .stepcarousel {
position: relative;
overflow: scroll;
}
.name_of_the_theme .stepcarousel .belt {
position: absolute;
left: 0;
top: 0;
}
.name_of_the_theme .stepcarousel .panel {
float: left;
overflow: hidden;
}
Integrating WP Carousel in our WordPress themes
Since WP Carousel 0.4, carousels support themes. Designers can create a WP Carousel theme and integrate it in their WordPress themes to create themes compatibles with WP Carousel.
Integrate a WP Carousel theme in a WordPress theme is easy. We’ll work with the function wp_carosel($carousel_id, $mode). $mode accepts three values: “show“, “get” and “array“. With “show“, WP Carousel will show the carousel (it’s the default value). With “get” WP Carousel will return the carousel and with “array” WP Carousel will return an array with the carousel’s content, ready to be used in a theme.
The following code will load a carousel with a theme integrated in our WordPress theme:
function my_theme_load_carousel($c_id)
{
$array = wp_carousel($c_id, 'array'); // We load the array
$config = $carousel_array['CONFIG']; // We load the config
$items = $carousel_array['ITEMS']; // We load the items
eval('if (!function_exists("wp_carousel_load_carousel_'.$c_id.'_js_code")) { function wp_carousel_load_carousel_'.$c_id.'_js_code() { wp_carousel_load_carousel_js('.$c_id.'); } }'); // We define a function to load the carousel's Javascript code
add_action('wp_footer', 'wp_carousel_load_carousel_'.$c_id.'_js_code'); // We load the carousel's Javascript code in the footer
require_once('wp-carousel-theme.php'); // We load our WP Carousel's theme
}
// We show here the carousel
my_theme_load_carousel(CAROUSEL_ID);
Creating an extra for WP Carousel
Since version 0.5, WP Carousel supports extras. With the extras WP Carousel can add any kind content to the carousel. The extras work like the themes, and there composed by two files: index.php and extra.php.
The file index.php contains the array with the information about the extra. Is very important filling correctly this array because it contains the name of the functions that load the content.
The following code is the index.php file of the extra Last tweet:
// Extra information
$extra['author'] = "Sumolari";
$extra['author_url']= "http://sumolari.com";
$extra['name'] = __('Last tweet', 'wp_carousel');
$extra['url'] = "http://sumolari.com/wp-carousel";
$extra['desc'] = __('Show the lastest tweet from a Twitter user', 'wp_carousel');
$extra['version'] = '1.0';
// Functions to get item's information
$extra['image_url_function'] = 'swpc_tweet_image_url';
$extra['link_url_function'] = 'swpc_tweet_link_url';
$extra['title_function'] = 'swpc_tweet_title';
$extra['desc_function'] = 'swpc_tweet_desc';
The last 4 indexes of the array contain the name of the functions that load the content. These names must be unique and can’t be repeated in any extra. These functions are defined in extra.php and they accept only one parameter: $id. They must return the content that we are looking for.
The following code is the extra.php file of the extra Last tweet:
// Returns the image URL
function swpc_tweet_image_url($id)
{
$format = 'json';
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$id}.{$format}"));
return $tweet[0]->user->profile_image_url;
}
// Returns the link to the item
function swpc_tweet_link_url($id)
{
$format = 'json';
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$id}.{$format}"));
return 'http://twitter.com/'.$id.'/status/'.$tweet[0]->id;
}
// Returns the title
function swpc_tweet_title($id)
{
$format = 'json';
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$id}.{$format}"));
return $tweet[0]->user->screen_name;
}
// Returns the desc
function swpc_tweet_desc($id)
{
$format = 'json';
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$id}.{$format}"));
return $tweet[0]->text;
}


Hay un total de 0 comentarios y 1 pingbacks / trackbacks.