I have a form that uploads posts to WordPress, and at the same time I can edit things like the meta data afterwards.
However using the WordPress edit_post_data works fine but a custom SQL query won’t work. I wonder why.
Works : update_post_meta($edit_id, 'lead_t', $_POST['lead_t']);
Doesn’t work :
$wpdb->query(
"UPDATE wp_postmeta (post_id, meta_key, meta_value)
VALUES ('".$edit_id."', 'lead_t', '".$_POST['lead_t']."')
WHERE post_id = '".$edit_id."' AND meta_key = 'lead_t'"
);
Does anyone know how to troubleshoot this or debug to find the reason?
Try the following…
global $wpdb;
$wpdb->query(
"
UPDATE {$wpdb->prefix}postmeta
SET post_id = {$edit_id}, meta_key = '{$meta_key}', meta_value="{$meta_value}"
WHERE post_id = {$edit_id} AND meta_key = '{$meta_key}'
"
);
//or using prepare
$wpdb->query(
$wpdb->prepare(
"
UPDATE {$wpdb->prefix}postmeta
SET post_id = %d, meta_key = %s, meta_value = %s
WHERE post_id = %d AND meta_key = %s
",
$edit_id,
$meta_key,
$meta_value,
$edit_id,
$meta_key
)
);
Also as a word of advice, set the following constants in your wp-config.php
file to enable debugging/error logging.
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
Errors should be logged to a file wp-content/debug.log
which should contain any errors relating to your query if it is malformed.