sábado, 19 de mayo de 2012

Wordpress: Custom Post Type y Auto guardado/Autosave

El siguiente post es debido a un pequeño problema al crear un Custom Post Type o Custom Meta Box, que cuando creamos un post, noticia y otro, los campos se borran solos cuando salimos del formulario o cuando se realiza el autosave de wordpress.

Un ejemplo de un Custom Post Type en nuestro functions.php :

add_action('init', 'texto');
function texto() {

    $labels = array(
        'name' => _x('texto', 'post type general name'),
        'singular_name' => _x('texto', 'post type singular name'),
        'add_new' => _x('Agregar Nuevo', 'texto'),
        'add_new_item' => __('Agregar Nuevo texto'),
        'edit_item' => __('Editar texto'),
        'new_item' => __('Nuevo texto'),
        'view_item' => __('Ver texto'),
        'search_items' => __('Buscar texto'),
        'not_found' =>  __('Nada encontrado'),
        'not_found_in_trash' => __('Nada encontrado en papelera'),
        'parent_item_colon' => ''
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => true,
        'menu_position' => null,
        'rewrite'   => true,
        'has_archive' => true,
        'supports' => array('title','editor', 'excerpt','thumbnail','comments','author','page-attributes')
    );

    register_post_type( 'texto' , $args );
}


function admin_init(){
    add_meta_box("opcion", "Opcion", "opcion", "texto", "normal", "low");
}


function opcion(){
    global $post;
    $custom = get_post_custom($post->ID);
    $texto= $custom["texto"][0];
    ?>
    Texto: < input name="texto" type="text" id="texto" value="texto; ?>" />

}


add_action('save_post', 'save_opcion');

function save_opcion(){
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
        return $post_id;

    global $post;
 
    update_post_meta($post->ID, "opcion", $_POST["texto"]);
}

Basta con incluir las siguiente 2 lineas en nuestro código:


    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
        return $post_id;


Estas se ejecutan cuando oprimimos el botón de publicar o cuando se realiza el autosave de wordpress.

No hay comentarios:

Templates
Templates