Verificar si un post existe

18 dic 2016, 12:30:23
Vistas: 14.4K
Votos: 1

¿Cómo puedo verificar si un post con un nombre, por ejemplo "Tiempo", existe? Si no existe, quiero crearlo.

function such_post_exists($title) {
global $wpdb;

$p_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );

if ( !empty ( $title ) ) {
    return (int) $wpdb->query("SELECT FROM $wpdb->posts WHERE post_title = $p_title");
}

return 0;
}
0
Todas las respuestas a la pregunta 2
3

WordPress tiene una función post_exists que devuelve el ID del post o 0 en caso contrario. Así que puedes hacer:

if ( 0 === post_exists( $title ) ) {
    **TU_CODIGO_AQUI**
}
18 dic 2016 12:40:33
Comentarios

¿Qué tal si cambio los lugares: if( 0 == post_exists($post_name) )

kilogram kilogram
18 dic 2016 12:52:06

@kilogram Funcionaría de ambas formas

Tunji Tunji
18 dic 2016 12:53:35

¿Pero eso también verifica publicaciones en la papelera? ¿Alguna otra alternativa? ¿Que solo verifique borradores/publicados?

sanjeev shetty sanjeev shetty
27 mar 2020 11:11:53
0

Si el Post no existe, créalo... SI existe, actualízalo.


$post_title = "Este Título Increíble";
$post_content = "Mi contenido de algo genial.";
$post_status = "publish"; //publish, draft, etc
$post_type = "page"; // o cualquier tipo de post deseado

/* Intentar encontrar el ID del post por su título si existe */
$found_post_title = get_page_by_title( $post_title, OBJECT, $post_type );
$found_post_id = $found_post_title->ID;

/**********************************************************
** Verificar si la página no existe, si es verdadero, crear un nuevo post 
************************************************************/
if ( FALSE === get_post_status( $found_post_id ) ): 

      $post_args = array(
        'post_title' => $post_title,
        'post_type' => $post_type,
        'post_content'=> $post_content,
        'post_status'  => $post_status,
        //'post_author'  => get_current_user_id(),

        /* Si tienes campos meta para ingresar datos */ 
        'meta_input'   => array(
            'meta_key1' => 'mi valor',
            'meta_key2' => 'mi otro valor',
        ),
      );      


      /* Añadir un nuevo post de WordPress en la base de datos, devolver su ID */ 
      $returned_post_id = wp_insert_post( $post_args );  

      /* Actualizar la plantilla de página solo si se usa "page" como post_type */ 
      update_post_meta( $returned_post_id, '_wp_page_template', 'my-page-template.php' ); 

      /* Añadir valores en campos meta. ¡Funciona con CAMPOS PERSONALIZADOS ACF! */
      $field_key = "Mi_Campo_CLAVE";
      $value = "mi valor personalizado";
      update_field( $field_key, $value, $returned_post_id );

      $field_key = "Mi_Otro_Campo_CLAVE";
      $value = "mi otro valor personalizado";
      update_field( $field_key, $value, $returned_post_id );

      /* Guardar un valor de checkbox o select */
      // $field_key = "Mi_Campo_CLAVE";
      // $value = array("rojo", "azul", "amarillo");
      // update_field( $field_key, $value, $returned_post_id );

      /* Guardar en un campo repetidor */
      // $field_key = "Mi_Campo_CLAVE";
      // $value = array(
      //   array(
      //     "ss_name" => "Foo",
      //     "ss_type" => "Bar"
      //   )
      // );
      // update_field( $field_key, $value, $returned_post_id );

      /* ¡Mostrar una respuesta! */
      echo "<span class='pg-new'><strong>". $post_title . " ¡Creado!</strong></span><br>";
      echo "<a href='".esc_url( get_permalink($returned_post_id) )."' target='_Blank'>". $post_title . "</a><p>";


else:        
/***************************
** SI EL POST EXISTE, actualízalo 
****************************/

      /* Actualizar post */
      $update_post_args = array(
        'ID'           => $found_post_id,
        'post_title'   => $post_title,
        'post_content' => $post_content,
      );

      /* Actualizar el post en la base de datos */
      wp_update_post( $update_post_args );

      /* Actualizar valores en campos meta */
      $field_key = "Mi_Campo_CLAVE";
      $value = "mi valor personalizado";
      update_field( $field_key, $value, $found_post_id );

      $field_key = "Mi_Otro_Campo_CLAVE";
      $value = "mi otro valor personalizado";
      update_field( $field_key, $value, $found_post_id );

      /* ¡Mostrar una respuesta! */
      echo "<span class='pg-update'><strong>". $post_title . " ¡Actualizado!</strong></span><br>"; 
      echo "<a href='".esc_url( get_permalink($found_post_id) )."' target='_Blank'>Ver</a> | <a href='post.php?post=".$found_post_id."&action=edit'>". $post_title . "</a><p>";

endif;

10 feb 2019 23:56:14