0

So here is the problem : I have created a metabox field for my posts and I want it to update a custom table (wp_location) in my WP datase... The idea is to update the table with the value of the POST method, but for some reason I seem to be using wrong the "wpdb" thing and it crashes every time on update... Here is my code for now :

add_action('add_meta_boxes','initialisation_metaboxes');
function initialisation_metaboxes() {
    add_meta_box('idMetaBox','test metabox','meta_function','post','side','high');
}

function meta_function(){
  echo '<label for="my_field">Test field : </label>';
  echo '<input id="my_field" type="text" name="my_field" />';
}

function save_metaboxes(){
  if(isset($_POST['my_field'])){
    $wpdb->update('wp_location', array('latitude' =>  $_POST['my_field']), array('refPost' => 198) );
  }

}

add_action('save_post','save_metaboxes');

I'm very new to Wordpress and metaboxes but I just can't find the solutions after hours of forum research...

My table is run in PhpMyAdmin and contains only 3 field for now :

  • idLoc (autoincremented by PhpMyAdmin)
  • refPost (I've inserted the value manually here - 198 - but there must be some easy way to retrieve it)
  • latitude (which is a simple text field for the moment)

Thanks for your help T_T

I know I could be using the post_meta table and functions, but I need a more complex database structure...

  • What means "it crashes"? What exactly happens? Any error message? Something in server logs? – cybmeta Nov 19 '16 at 10:03
  • I have an error 500 when I save my edits on post and of course the table is not updated – Hub Lot Nov 19 '16 at 10:52
0

Variable scope - you need to globalise $wpdb before you can use it inside your function:

function save_metaboxes() {
    global $wpdb;

    // Rest of your code
}
  • It worked just fine. I had tried to globalise $wpdb outside the function, when it had to be inside in order to work... Thanks a lot! – Hub Lot Nov 19 '16 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.