1

Alguien sabe como crear un post en Wordpress por medio de algun script PHP, necesito crear post semi-automaticos en una web periodicamente, mi idea es crear un codigo php en la misma web con el que por medio de un cron se active cada cierto tiempo y se cree un post claro esta mandandole el titulo contenido featured image y tags si alguien me puede ayudar por favor con algo que me oriente se lo agradeceria mucho

1
  • 1
    Puedes hacerlo por correo. Manda los post a alguna cuenta que pueda leer tu WP y ya.
    – toledano
    el 10 mar. 2017 a las 5:18

1 respuesta 1

3

Existen varias posibilidades:

A. USANDO LAS FUNCIONES DE WORDPRESS

Podrías no sólo crear, sino también actualizar. Ver:

  1. $post
  2. wp_insert_post()

Algún o algunos includeson necesarios

Código de ejemplo

if ( ! function_exists( 'PostCreator' ) ) {

    function PostCreator(
        $name      = 'AUTO POST',
        $type      = 'post',
        $content   = 'DUMMY CONTENT',
        $category  = array(1,2),
        $template  = NULL,
        $author_id = '1',
        $status    = 'publish'
    ) {

        define( POST_NAME, $name );
        define( POST_TYPE, $type );
        define( POST_CONTENT, $content );
        define( POST_CATEGORY, $category );
        define( POST_TEMPLATE, '' );
        define( POST_AUTH_ID, $author_id );
        define( POST_STATUS, $status );

        if ( $type == 'page' ) {
            $post      = get_page_by_title( POST_NAME, 'OBJECT', $type );
            $post_id   = $post->ID;
            $post_data = get_page( $post_id );
            define( POST_TEMPLATE, $template );
        } else {
            $post      = get_page_by_title( POST_NAME, 'OBJECT', $type );
            $post_id   = $post->ID;
            $post_data = get_post( $post_id );
        }

        function hbt_create_post() {
            $post_data = array(
                'post_title'    => wp_strip_all_tags( POST_NAME ),
                'post_content'  => POST_CONTENT,
                'post_status'   => POST_STATUS,
                'post_type'     => POST_TYPE,
                'post_author'   => POST_AUTH_ID,
                'post_category' => POST_CATEGORY,
                'page_template' => POST_TEMPLATE
            );
            wp_insert_post( $post_data, $error_obj );
        }

        if ( ! isset( $post ) ) {
            add_action( 'admin_init', 'hbt_create_post' );
            return $error_obj;
        }

    }
}

/* All available options for PostCreator()

PostCreator( 'TITLE' , 'POST TYPE' , 'POST CONTENT' , 'POST CATEGORY' , 'TEMPLATE FILE NAME' , 'AUTHOR ID NUMBER' , 'POST STATUS');

TITLE - HTML Stripped Out. Simple String.
POST TYPE - Post type slug. Eg 'post' or 'page'. Custom Post Types are supported.
POST CONTENT - Content of the Post/Page. HTML allowed.
POST CATEGORY - An array of the integer ID's of the category/categories you want to link to your post
TEMPLATE FILE NAME - File name of the template. Only for Pages. In the format 'file_name.php'.
AUTHOR ID NUMBER - Integer value. Default is 1.
POST STATUS - Available options; [ 'draft' | 'publish' | 'pending'| 'future' | 'private' | custom registered status ]

If successful, PostCreator() returns nothing.
If there is an error PostCreator() returns a WP_error object.

*/

PostCreator( 'My Lorem Ipsum', 'page', 'With a sizable serving of Dolor. This was created using Harri Bell-Thomas\'s PostCreator function.' );

Fuente de este código


B. USANDO LA (CUESTIONADA) API XML-RPC

En WordPress, el protocolo XMLRPC es una especie de interfaz que actúa como API para aplicaciones externas y que nos permite interactuar con una instalación de WordPress utilizando aplicaciones o servicios externos. Al funcionar como una interfaz externa es casi como una “puerta de entrada” la cual puede ser en consecuencia atacada fácilmente desde el exterior causando un alto consumo de recursos al ejecutarse una y otra vez el proceso de autentificación.

En muchos sitios esta API es puesta en cuestión y cuando no se usa es aconsejable desactivarla (ver por ejemplo).

De todos modos, aquí tienes un ejemplo:

function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8') {
    $title = htmlentities($title,ENT_NOQUOTES,$encoding);
    $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);

    $content = array(
        'title'=>$title,
        'description'=>$body,
        'mt_allow_comments'=>0,  // 1 to allow comments
        'mt_allow_pings'=>0,  // 1 to allow trackbacks
        'post_type'=>'post',
        'mt_keywords'=>$keywords,
        'categories'=>array($category)
    );
    $params = array(0,$username,$password,$content,true);
    $request = xmlrpc_encode_request('metaWeblog.newPost',$params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_URL, $rpcurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    $results = curl_exec($ch);
    curl_close($ch);
    return $results;
?>

Fuente de este código


C. INSERTANDO EN LA BASE DE DATOS MYSQL

Las entradas de WP son almacenadas en una Base de Datos MySQL. No será difícil crear un script que se conecte a la BD y cree un post insertando los datos que envíes en la/las tablas correspondientes.

2
  • Gracias lo logre usando las funciones de Wordpress pero hay que añadir este include: require(dirname(FILE) . '/wp-load.php'); el 10 mar. 2017 a las 4:44
  • Muy bueno, se dejó adaptar perfectamente a lo que quería.
    – Annier
    el 29 mar. 2019 a las 0:05

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.