Create Facebook applications with CodeIgniter
Learn how to incorporate the Facebook SDK into the CodeIgniter framework, using the available functions to create applications. …
Learn how to incorporate the Facebook SDK into the CodeIgniter framework, using the available functions to create applications. …
Creo que para ciertos blogs es muy útil ofrecer la opción de añadir OpenSearch para que la gente puede realizar búsquedas en nuestro blog. Algo también bastante útil es que nos ofrezca sugerencias de búsquedas (tal y como hace Google). Para ello tan sólo hay que añadir una opción al XML de OpenSearch y modificar nuestro functions.php.
En el fichero XML deberemos añadir la siguiente etiqueta:
Y añadir xmlns:suggestions="http://www.opensearch.org/specifications/opensearch/extensions/suggestions/1.1"
a la etiqueta inicial OpenSearchDescription
Yo en este caso he preferido usar una URL amigable, sobre todo para practicar con el wp_rewrite, pero se podría hacer perfectamente con una variable con parámetros.
Una vez cambiado el opensearch.xml deberemos modificar el functions.php, para lo cual tendremos que coger el término que se quiere sugerir y buscar entre las categorías y tags y entre los títulos de los posts para así mostrar una unión de ambos. Las categorías se ordenarán por el número de veces que aparece y los posts por fecha descendente.
add_filter('init','suggestion_init');
add_filter('query_vars','suggestion_insertMyRewriteQueryVars');
add_filter('rewrite_rules_array','suggestion_rewrite');
// Acciones iniciales
function suggestion_init(){
// Reescribe las reglas
global $wp_rewrite;
$wp_rewrite->rewrite_rules();
// Obtiene el termino a buscar
$req = explode('/', substr($_SERVER['REQUEST_URI'], 1), 2);
if ($req[0] == 'suggestion') {
$result = wp_cache_get( 'suggestion_'.$req[1] );
if ( false == $result ) {
global $wpdb;
$list = array();
// Recupera las 4 categorias/tags que coincidan
$res = $wpdb->get_results("select name from $wpdb->terms t, $wpdb->term_taxonomy tx where name like '%".$req[1]."%' and t.term_id = tx.term_id group by name order by count desc limit 4");
foreach ($res as $item) $list[] = $item->name;
// Recupera las 4 anotaciones que coincidan
$res = $wpdb->get_results("select post_title from $wpdb->posts where post_title like '%".$req[1]."%' order by ID desc limit 4");
foreach ($res as $item) $list[] = $item->post_title;
// Devuelve en formato JSON
$result = json_encode(array($req[1], $list));
wp_cache_set( 'suggestion_'.$req[1], $result );
}
echo $result;
exit();
}
}
// Permite que WP acepte un nueva parametro en la query de la URL
function suggestion_insertMyRewriteQueryVars($vars) {
array_push($vars, 'suggestion');
return $vars;
}
// Reescribe la regla
function suggestion_rewrite($rules)
{
$newrules = array();
$newrules['suggestion/([^/]+)/(.*)$'] = 'index.php?suggestion=$matches[1]';
return $newrules + $rules;
}
En el código he añadido caché, porque es altamente recomendable, puediendo usar el plugin WP File Cache. También debo decir que me encontré con el problema del timeout que tiene Firefox para esperar la respuesta para la sugerencia, muy pequeño para mi servidor, por lo que si quieres modificarlo, busca el fichero nsSearchSuggestions.js y modifica el valor de _suggestionTimeout.
TwitPic es un servicio que se utiliza para subir fotos que luego publicas en Twitter. Si estás realizando una aplicación que tira de Twitter y quieres dar la oportunidad al usuario de subir sus fotos puedes hacer uso de esta aplicación y su API (es necesario darse de alta):
$twitpic = new TwitPic($api_key, $consumer_key, $consumer_secret, $oauth_token, $oauth_secret);
try {
/*
* Retrieves all images where the user is facetagged
*/
$user = $twitpic->faces->show(array('user'=>'meltingice'));
print_r($user->images);
$media = $twitpic->media->show(array('id'=>1234));
echo $media->message;
$user = $twitpic->users->show(array('username'=>'meltingice'), array('process'=>false, 'format'=>'xml'));
echo $user; // raw XML response data
/*
* Uploads an image to TwitPic
*/
$resp = $twitpic->upload(array('media'=>'path/to/file.jpg', 'message'=>'This is an example'));
print_r($resp);
/*
* Uploads an image to TwitPic AND posts a tweet
* to Twitter.
*
* NOTE: this still uses v2 of the TwitPic API. This means that the code makes 2 separate
* requests: one to TwitPic for the image, and one to Twitter for the tweet. Because of this,
* understand this call may take a bit longer than simply uploading the image.
*/
$resp = $twitpic->uploadAndPost(array('media'=>'path/to/file.jpg', 'message'=>'Another example'));
print_r($resp);
} catch (TwitPicAPIException $e) {
echo $e->getMessage();
}
La sorpresa que me he llevado cuando Dinahosting, en el hosting compartido, no permite el uso de la función mail si no le indicas en las cabeceras un email registrado en el dominio. Algo así:
$to = 'destinatario@dominio.com';
$subject = 'Prueba';
$email_text = 'El contenido del email';
$headers = "From: Yo mismo
MIME-Version: 1.0
Content-type: text/html; charset=utf-8";
$success = mail($to, $subject, $email_text, $headers);
Normalmente, cuando usas mail, pues pones el to, el subject, el content y te olvidas, pero en este caso debes indicar el header con un from. El problema viene con el 99.9% de los plugins o themes que ofrecen formularios de contacto, que simulan el envío de email por parte del usuario para que cuando te llegue el email, le des a un reply y listo. En Dinahosting, con hosting compartido no se puede.
Para solucionar esto es necesario hacer una chapuza enorme, cambiar el FROM de las cabeceras de wp_mail, para lo que deberemos añadir esto en nuestro functions.php:
add_filter( 'wp_mail_from', 'error_dinahosting');
function error_dinahosting($from) {
return get_bloginfo('admin_email');
}
Puedo entender y se agradece la seguridad de Dinahosting, pero creo que esto es un error.