Comprobar si existe el título del Post, Insertar post si no existe, Agregar # Incremental a Meta si existe

15 jul 2012, 21:58:08
Vistas: 37.5K
Votos: 14

Ya tengo una función donde un usuario envía un formulario y crea un post personalizado...

<?php 
$postTitle = $_POST['post_title'];
$submit = $_POST['submit'];

if(isset($submit)){
    global $user_ID;
    
    // Comprobar si el post existe
    $post_exists = get_page_by_title($postTitle, OBJECT, 'stuff');
    
    if(!$post_exists) {
        // Si el post no existe, créalo
        $new_post = array(
            'post_title' => $postTitle,
            'post_content' => '',
            'post_status' => 'publish',
            'post_date' => date('Y-m-d H:i:s'),
            'post_author' => '',
            'post_type' => 'stuff',
            'post_category' => array(0)
        );
        
        $post_id = wp_insert_post($new_post);
        add_post_meta($post_id, 'times', '1');
    } else {
        // Si el post existe, incrementa el contador
        $times = get_post_meta($post_exists->ID, 'times', true);
        $times = intval($times) + 1;
        update_post_meta($post_exists->ID, 'times', $times);
    }
}

Quiero comprobar si existe el título del post personalizado, entonces si NO existe, proceder a crear el post con un #1 en el campo meta, y si existe, simplemente agregar 1 al campo meta

0
Todas las respuestas a la pregunta 6
1
12

Un método más actualizado puede utilizar la función post_exists() de la siguiente manera:

if( isset( $_POST['submit'] ) ){

   $post_title = sanitize_title( $_POST['post_title'] );

   $new_post = array(
       'post_title' => $post_title,
       'post_content' => '',
       'post_status' => 'publish',
       'post_date' => date('Y-m-d H:i:s'),
       'post_author' => '',
       'post_type' => 'stuff',
       'post_category' => array(0)
   );

   $post_id = post_exists( $post_title ) or wp_insert_post( $new_post );

   update_post_meta( $post_id, 'times', '1' );

}
29 nov 2017 07:19:14
Comentarios

No está muy claro si el OP quería incrementar el campo meta en 1 si el post existe, o simplemente establecer el campo meta en 1. Lo anterior siempre lo establecerá en 1. Para incrementarlo, el operador ternario $post_id = post_exists[...] debería desglosarse en un if / else para poder incrementar el campo meta.

Tim Hallman Tim Hallman
8 nov 2018 21:50:18
8

Esto necesitaría una consulta.

Continuando con tu código:

<?php
$postTitle = $_POST['post_title'];
$submit = $_POST['submit'];

if(isset($submit)){

    global $user_ID, $wpdb;

    $query = $wpdb->prepare(
        'SELECT ID FROM ' . $wpdb->posts . '
        WHERE post_title = %s
        AND post_type = \'stuff\'',
        $postTitle
    );
    $wpdb->query( $query );

    if ( $wpdb->num_rows ) {
        $post_id = $wpdb->get_var( $query );
        $meta = get_post_meta( $post_id, 'times', TRUE );
        $meta++;
        update_post_meta( $post_id, 'times', $meta );
    } else {
        $new_post = array(
            'post_title' => $postTitle,
            'post_content' => '',
            'post_status' => 'publish',
            'post_date' => date('Y-m-d H:i:s'),
            'post_author' => '',
            'post_type' => 'stuff',
            'post_category' => array(0)
        );

        $post_id = wp_insert_post($new_post);
        add_post_meta($post_id, 'times', '1');
    }
}

Debería funcionar

16 jul 2012 00:08:14
Comentarios

Quizás quieras agregar AND post_status = 'publish' a la consulta inicial para que solo devuelva posts publicados.

Barry Carlyon Barry Carlyon
16 jul 2012 00:09:21

¡Gracias nuevamente por la ayuda! Sin embargo, por alguna razón los posts no están llegando a la base de datos... ni los nuevos ni las actualizaciones de los antiguos.

marctain marctain
16 jul 2012 02:28:53

¿Hay algún error tipográfico en alguna parte? No logro identificarlo.

marctain marctain
16 jul 2012 06:32:22

Haré una prueba cuando llegue a casa del trabajo

Barry Carlyon Barry Carlyon
16 jul 2012 13:48:15

Fallo épico por mi parte WHERE post_title = %d debería ser WHERE post_title = %s golpe en la cabeza

Barry Carlyon Barry Carlyon
16 jul 2012 22:10:22

¡Le pasa a los mejores! Vale, entonces los nuevos posts se están insertando ahora, pero el valor meta para "times" no se está incrementando. Sin embargo, se está creando un nuevo valor meta llamado "2". Tampoco se autoincrementa.

marctain marctain
16 jul 2012 22:18:46

Ups, olvidé actualizar esa línea también. update_post_meta( $post_id, $meta ); debería ser update_post_meta( $post_id, 'times', $meta );

Barry Carlyon Barry Carlyon
16 jul 2012 22:19:58

¡Ah, eso tiene sentido! Debí haberlo visto también. Muchas gracias. ¡Victoria épica para ti!

marctain marctain
16 jul 2012 22:21:19
Mostrar los 3 comentarios restantes
1

Puedes usar la función get_page_by_title() de WordPress:

<?php $postTitle = $_POST['post_title'];
$submit = $_POST['submit'];


if(isset($submit)){
    $customPost = get_page_by_title($postTitle, OBJECT, 'stuff');

    if(!is_null($customPost)) {
       $meta = get_post_meta($customPost->ID, 'times', true);
       $meta++;
       update_post_meta($customPost->ID, 'times', $meta);

       return
    }

    global $user_ID;

    $new_post = array(
        'post_title' => $postTitle,
        'post_content' => '',
        'post_status' => 'publish',
        'post_date' => date('Y-m-d H:i:s'),
        'post_author' => '',
        'post_type' => 'stuff',
        'post_category' => array(0)
    );

    $post_id = wp_insert_post($new_post);
    add_post_meta($post_id, 'times', '1');

}
16 may 2016 12:57:03
Comentarios

Hola Alex, bienvenido a WPSE. No dudes en hacer el recorrido. Nos gusta vivir bajo el principio de enseñar a pescar en lugar de simplemente dar el pescado. ¿Te importaría editar tu publicación para agregar una explicación de por qué esto resuelve el problema del OP?

Tim Malone Tim Malone
16 may 2016 13:27:26
1

@Tim Hallman buena respuesta. Usa la función post_exists() para verificar si el post existe o no. Para más detalles visita https://developer.wordpress.org/reference/

Documentación para desarrolladores

20 mar 2018 13:13:49
Comentarios

Para usar esta función en el frontend, se necesita algo de trabajo.

Tami Tami
10 jun 2021 02:44:06
1

Puedes hacerlo por ID


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

/* Intentar encontrar el ID del post por el 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, devuelve 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, actualizarlo 
****************************/

      /* 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:53:23
Comentarios

En realidad, es más seguro usar las 2 funciones integradas de WP que están diseñadas para esto, post_exists y wp_insert_post como en la respuesta de @TimHallman. Cuanto más código innecesario introduzcas, mayor será la posibilidad de introducir errores o problemas de mantenimiento a largo plazo.

FluffyKitten FluffyKitten
23 feb 2019 19:57:55
0
-1

WordPress verificar si existe una publicación por título

function wp_exist_post_by_title( $title ) {
    global $wpdb;
    $return = $wpdb->get_row( "SELECT ID FROM wp_posts WHERE post_title = '" . $title . "' && post_status = 'publish' && post_type = 'post' ", 'ARRAY_N' );
    if( empty( $return ) ) {
        return false;
    } else {
        return true;
    }
}

// uso
if( wp_exist_post_by_title( $post->name ) ) {
// la publicación existe
} else { 
// la publicación no existe
}
13 abr 2015 16:51:40