- Mensajes
- 115
- Puntuación de reacción
- 0
Hola, quiero compartir un código para crear post en WordPress de forma automatizada.
Vamos a obtener las películas de algún sitio web para publicarlas en nuestra web.
Como ejemplo he tomado a Ver Aquarius: Primera Temporada / Temporada 1 Online Gratis Pelicula en Español
A tener en cuenta que se puede programar un scraper que vaya guardando todas las url de todas las películas de ese sitio web y luego ir tomando cada url para irla scrapeado y guardando en WP
Definimos el header
Recuperamos en enlace de la base de datos
Ahora vamos a obtener el titulo e imagen.
Copiamos la imagen a nuestro servidor
Declaramos los valores a guardar
Leemos los archivos de WordPress, este script debe alojar en la carpeta wp-content
Vamos a crear el post, dependerá de la plantilla utilizada los meta
Este script necesita que se adapte a cada plantilla pero ya he indicado lo esencial.
Los datos que cambian son el sitio a scrapear y el contenido que se obtiene como imágenes, descripción, enlaces, etc
Y también la estructura de la plantilla.
Por último sólo se tiene que programar el script con un cron para que vaya publicando cada x tiempo.
Cualquier duda por favor comentar.
Vamos a obtener las películas de algún sitio web para publicarlas en nuestra web.
Como ejemplo he tomado a Ver Aquarius: Primera Temporada / Temporada 1 Online Gratis Pelicula en Español
A tener en cuenta que se puede programar un scraper que vaya guardando todas las url de todas las películas de ese sitio web y luego ir tomando cada url para irla scrapeado y guardando en WP
Definimos el header
PHP:
<?php
header('Content-Type: text/html; charset=utf-8');
// Set the timezone so times are calculated correctly
Recuperamos en enlace de la base de datos
PHP:
//recuperar enlaces
$recuperar_enlaces = "SELECT * FROM table WHERE scraper=0 ORDER by id ASC LIMIT 1";
$enlaces = mysqli_query($conexion,$recuperar_enlaces);
while($enlace = mysqli_fetch_array($enlaces)):
$id_enlace = $enlace["id"];
$enlace_escrapear = $enlace["pelicula"];
echo '<a href="' . $enlace_escrapear . '" target="_blank">'. $id_enlace .' - Ir a la película</a><br>';
$curl = curl_init($enlace_escrapear);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$page = curl_exec($curl);
if(curl_errno($curl)) // check for execution errors
{
echo 'Scraper error: ' . curl_error($curl);
exit;
}
curl_close($curl);
Ahora vamos a obtener el titulo e imagen.
PHP:
////////// Titulo //////////
$regex = '></span> (.*?)<a href=/s';
preg_match_all($regex, $page, $rnombre);
$titulo = $rnombre[1][0];
////////// Imagen //////////
$regex = '<img src="(.*?)" height="250"/s';
preg_match_all($regex, $page, $rimagen);
$imagen = trim($rimagen[1][0]);
Copiamos la imagen a nuestro servidor
PHP:
$mes = date('m');
$ruta_imagen = "../uploads/2015/" . $mes. "/". $alias. ".jpg";
$ruta_img_corta = "2015/" . $mes. "/". $alias. ".jpg";
$imagen = file_get_contents($imagen);
file_put_contents($ruta_imagen, $imagen);
Declaramos los valores a guardar
PHP:
$hoy = date("Y-m-d H:i:s");
$post_author = 1;
$post_status = "publish";
$post_name = $alias;
$post_type = "portfolio";
Leemos los archivos de WordPress, este script debe alojar en la carpeta wp-content
PHP:
// Load WordPress
require_once '../../wp-load.php';
require_once ABSPATH . '/wp-admin/includes/taxonomy.php';
Vamos a crear el post, dependerá de la plantilla utilizada los meta
PHP:
// Create post
$id_post = wp_insert_post(array(
'post_title' => $titulo,
'post_content' => $contenido_es,
'post_date' => $hoy,
'post_author' => 1,
'post_type' => 'portfolio',
'post_status' => 'publish',
));
if ($id_post) {
// $filename should be the path to a file in the upload directory.
$filename = $ruta_imagen;
// The ID of the post this attachment is for.
$parent_post_id = $id_post;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
$filename = $ruta_imagen;
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( '../../wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
// Set category - create if it doesn't exist yet
wp_set_post_terms($id_post,'5', 'portfolio_categories');
// Add meta data, if required
add_post_meta($id_post, 'rttheme_project_info', $project_info);
add_post_meta($id_post, 'rttheme_project_info_title', 'Detalles');
add_post_meta($id_post, 'rttheme_portfolio_desc', $descripcion);
add_post_meta($id_post, 'rttheme_featured_image_usage', 'slider');
add_post_meta($id_post, 'rttheme_portfolio_post_format', 'image');
add_post_meta($id_post, 'rtthemeportfolio_max_image_height', 400);
add_post_meta($id_post, '_thumbnail_id',$attach_id);
echo "pelicula Importada con éxito " . $enlace_escrapear;
$actualizar_scraper_enlace = "UPDATE table SET scraper=1 WHERE id='{$id_enlace}'";
mysqli_query($conexion,$actualizar_scraper_enlace);
} else {
echo "WARNING: Failed to insert post into WordPress\n";
}
endwhile;
?>
Este script necesita que se adapte a cada plantilla pero ya he indicado lo esencial.
Los datos que cambian son el sitio a scrapear y el contenido que se obtiene como imágenes, descripción, enlaces, etc
Y también la estructura de la plantilla.
Por último sólo se tiene que programar el script con un cron para que vaya publicando cada x tiempo.
Cualquier duda por favor comentar.