2012-03-28 14 views
18

Quiero agregar un nuevo campo de casilla de verificación dentro del bloque Publicar en la página agregar/editar publicación. ¿Alguien tiene idea de cómo hacer eso?¿Cómo agregar un campo en la página de publicación de edición dentro del cuadro Publicar en Wordpress?

+0

Check this -> http://wordpress.org/extend/plugins/more-fields/ – Rikesh

+0

He comprobado más campos. ¿No podemos simplemente agregar un nuevo campo de alguna otra manera, como add_meta_box()? – rbncha

Respuesta

20

fin he encontrado la solución. Espero que sea de utilidad para alguien.

add_action('post_submitbox_misc_actions', 'publish_in_frontpage'); 
function publish_in_frontpage($post) 
{ 
    $value = get_post_meta($post->ID, '_publish_in_frontpage', true); 
    echo '<div class="misc-pub-section misc-pub-section-last"> 
     <span id="timestamp">' 
     . '<label><input type="checkbox"' . (!empty($value) ? ' checked="checked" ' : null) . 'value="1" name="publish_in_frontpage" /> Publish to frontpage</label>' 
    .'</span></div>'; 
} 

function save_postdata($postid) 
{ 
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return false; 
    if (!current_user_can('edit_page', $postid)) return false; 
    if(empty($postid) || $_POST['post_type'] != 'article') return false; 

    if($_POST['action'] == 'editpost'){ 
     delete_post_meta($postid, 'publish_in_frontpage'); 
    } 

    add_post_meta($postid, 'publish_in_frontpage', $_POST['publish_in_frontpage']); 
} 
+0

Buen hallazgo. Nunca pensé poner algo en esa caja, pero tener el método (algo indocumentado) de hacerlo es genial. ¡Destacó esto para su uso posterior! –

+2

Solo una pequeña actualización: 'publish_in_frontpage()' parece no tener parámetros, así que usé 'global $ post;' dentro, funciona bien. – frnhr

+0

Este código está lejos de ser completo/correcto y no funciona, dudo que haya funcionado alguna vez. Agregué mi código fijo/comentado a continuación. – user2019515

-2

Utilice el complemento Advanced Custom Fields para WordPress.

+0

No encuentro una forma de agregar una casilla dentro del bloque ** Publicar ** en los campos personalizados avanzados – rbncha

2

¡Bien !, no he podido encontrar una solución para agregar un campo en Publicar bloque. Para la solución temporal, he agregado un nuevo bloque simplemente agregando códigos simples como a continuación.

add_action('admin_init', 'category_metabox');

//add new publish to frontpage box 
add_meta_box( 
    'publish_in_frontpage', 
    'Publish in Frontpage', 
    'publish_in_frontpage_callback', 
    'article', 
    'side', 
    'high' 
); 

function publish_in_frontpage_callback($post) 
{ 
    $value = get_post_meta($post->ID, '_publish_in_frontpage', true); 
    echo '<label><input type="checkbox"' . (!empty($value) ? ' checked="checked" ' : null) . 'value="1" name="publish_in_frontpage" /> Publish to frontpage</label>'; 
} 

add_action('save_post', 'save_postdata'); 

function save_postdata($postid) 
{ 
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return false; 
    if (!current_user_can('edit_page', $postid)) return false; 
    if(empty($postid) || $_POST['post_type'] != 'article') return false; 

    if($_POST['action'] == 'editpost'){ 
     delete_post_meta($postid, 'publish_in_frontpage'); 
    } 

    add_post_meta($postid, 'publish_in_frontpage', $_POST['publish_in_frontpage']); 
} 

12

código rbncha 's no funciona fuera de la caja y necesitaba una gran cantidad de ajustes, el código de abajo es lo que ocurrió. He agregado algunos comentarios que explican todo a fondo.

El siguiente código agrega una casilla de verificación en el bloque de publicación de publicaciones (puede cambiar fácilmente el tipo de publicación), y almacena/recupera el valor en/desde la base de datos. Con algunos ajustes menores, puede agregar fácilmente un campo de texto o cualquier cosa que desee.

Debe tenerse en cuenta que usted tiene que cambiar my_ a una única clave para su tema o plug-in!

add_action('post_submitbox_misc_actions', 'my_featured_post_field'); 
function my_featured_post_field() 
{ 
    global $post; 

    /* check if this is a post, if not then we won't add the custom field */ 
    /* change this post type to any type you want to add the custom field to */ 
    if (get_post_type($post) != 'post') return false; 

    /* get the value corrent value of the custom field */ 
    $value = get_post_meta($post->ID, 'my_featured_post_field', true); 
    ?> 
     <div class="misc-pub-section"> 
      <?php //if there is a value (1), check the checkbox ?> 
      <label><input type="checkbox"<?php echo (!empty($value) ? ' checked="checked"' : null) ?> value="1" name="my_featured_post_field" /> Featured on frontpage</label> 
     </div> 
    <?php 
} 

add_action('save_post', 'my_save_postdata'); 
function my_save_postdata($postid) 
{ 
    /* check if this is an autosave */ 
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return false; 

    /* check if the user can edit this page */ 
    if (!current_user_can('edit_page', $postid)) return false; 

    /* check if there's a post id and check if this is a post */ 
    /* make sure this is the same post type as above */ 
    if(empty($postid) || $_POST['post_type'] != 'post') return false; 

    /* if you are going to use text fields, then you should change the part below */ 
    /* use add_post_meta, update_post_meta and delete_post_meta, to control the stored value */ 

    /* check if the custom field is submitted (checkboxes that aren't marked, aren't submitted) */ 
    if(isset($_POST['my_featured_post_field'])){ 
     /* store the value in the database */ 
     add_post_meta($postid, 'my_featured_post_field', 1, true); 
    } 
    else{ 
     /* not marked? delete the value in the database */ 
     delete_post_meta($postid, 'my_featured_post_field'); 
    } 
} 

Si desea leer más acerca de los campos personalizados ver aquí: http://codex.wordpress.org/Custom_Fields

+0

'compruebe si el campo personalizado se envía' Puede agregar un campo oculto antes de la casilla de verificación con el mismo nombre y valor = 0. – gaRex

+0

¿Eso parece una mala práctica? ¿Solución Hacky? – user2019515

+0

no, muchos marcos lo hacen. Entonces esto podría ser nombrado como práctica existente. – gaRex

Cuestiones relacionadas