Cómo usar consultas de actualización y eliminación en WordPress

5 may 2015, 09:40:21
Vistas: 65.9K
Votos: 4

Primero escribí manualmente las consultas de actualización, eliminación, inserción y selección y ejecuté los datos con la función mysql_query

De esta manera:

Consulta Select

$prefix = $wpdb->prefix;
$postSql = "SELECT DISTINCT post_id
            FROM " . $prefix . "postmeta As meta
            Inner Join " . $prefix . "posts As post
            On post.ID = meta.post_id
            Where post_type = 'product' 
            And post_status = 'publish'
            And meta_key Like '%product_img%'";
$postQry = mysql_query($postSql);
while ($postRow = mysql_fetch_array($postQry)) {
     $post_id = $postRow['post_id'];
}

Consulta Insert

$insert_images = "Insert Into " . $prefix . "postmeta(post_id,meta_key,meta_value) Value('$post_id','$meta_key','$data_serialize')";
        mysql_query($insert_images);

Consulta Update:

$update_price = "Update " . $prefix . "postmeta
                         Set meta_key = 'wpc_product_price'
                         Where post_id = $supportMetaID
                         And meta_key Like '%product_price%'";
 mysql_query($update_price);

Consulta Delete

mysql_query("Delete From " . $prefix . "postmeta Where meta_key IN ('product_img1','product_img2','product_img3')");

Todas las consultas funcionan perfectamente... pero ahora quiero incorporar todas las consultas en consultas de WordPress.

También puedo usar consultas de WordPress como

$wpdb->get_results( "SELECT id, name FROM mytable" );
$wpdb->insert( 
    'table', 
    array( 
        'column1' => 'value1', 
        'column2' => 123 
    ), 
);
$wpdb->update( 
    'table', 
    array( 
        'column1' => 'value1',  // cadena
        'column2' => 'value2'   // entero (número)
    ), 
    array( 'ID' => 1 )
);
$wpdb->delete( 'table', array( 'ID' => 1 ) );

Pero como pueden ver, uso condiciones and / or en mis consultas. ¿Alguien puede ayudarme a incorporar mis consultas en WordPress?

1
Comentarios

WordPress ofrece la Clase $wpdb para hacer todo esto. Pero una consulta como la primera puede lograrse fácilmente con WP_Query() con menos esfuerzo.

Mayeenul Islam Mayeenul Islam
5 may 2015 11:18:49
Todas las respuestas a la pregunta 2
0

Sobre ACTUALIZAR+INSERTAR:

He creado una función para mí mismo, y también podría ayudarte, por ejemplo:

UPDATE_OR_INSERT('wp_users',  array('gender'=>'female'), array('name'=>'Monika') );

que ACTUALIZARÁ UN VALOR en la columna (donde name=monika), pero en caso de que ese valor no exista, entonces creará un nuevo registro en la base de datos.
¿Por qué esto es necesario? Porque hasta donde yo sé, no existe una función sofisticada en WP que actualice datos en la DB (si el valor existe) o inserte datos (si no existe). En su lugar, usamos: $wpdb->update() o $wpdb->insert(). Así que usa esta función, ayuda:

function UPDATE_OR_INSERT($tablename, $NewArray, $WhereArray){          global $wpdb; $arrayNames= array_keys($WhereArray);
    //convertir array a STRING
    $o=''; $i=1; foreach ($WhereArray as $key=>$value){ $o .= $key . ' = \''. $value .'\''; if ($i != count($WhereArray)) { $o .=' AND '; $i++;}  }
    //verificar si ya existe
    $CheckIfExists = $wpdb->get_var("SELECT ".$arrayNames[0]." FROM ".$tablename." WHERE ".$o);
    if (!empty($CheckIfExists))  { return $wpdb->update($tablename, $NewArray,  $WhereArray );}
    else                         { return $wpdb->insert($tablename,     array_merge($NewArray, $WhereArray) );  } 
}
1 sept 2016 14:52:01
0

Consulta de Actualización:

$table = $wpdb->prefix . 'tablename';

$wpdb->update( $table_name, array( 'role_id' => 1),array('user_id'=>$user_id));

Consulta de Eliminación:

$wpdb->delete( $table, array( 'id' => $id ) );
4 may 2020 13:20:46