2

I want to use $wpdb in a theme file, but it doesn't work. My code is bellow:

<?php


$action = $_POST['action'];
$updateRecordsArray = $_POST['recordsArray'];


if ($action == "updatelist") {

    $listingCounter = 1;
    $column = $_GET['column'];

    foreach ($updateRecordsArray as $key=>$value) {

    $wpdb->update('wp_postmeta', array('meta_value'=>$column), array('post_id'=>$value, 'meta_key'=>'dbt_text') );
    $wpdb->update('wp_posts', array('menu_order'=>$listingCounter), array('ID'=>$value) );

    $listingCounter = $listingCounter + 1;  

    }
}


?>

I think that $wpdb must be declared global or I must include certain files. Can someone please help me on this?

4
  • What doesn't work? What errors do you get?
    – Pekka
    Commented Aug 31, 2011 at 7:05
  • Undefined variable: wpdb
    – zuzuleinen
    Commented Aug 31, 2011 at 7:07
  • It's probably a scope issue. Is this being included from within a function? Are you initializing Wordpress?
    – Pekka
    Commented Aug 31, 2011 at 7:08
  • I don't think so. The code bellow is all that i have in the php file.
    – zuzuleinen
    Commented Aug 31, 2011 at 7:22

2 Answers 2

3

You need to connect your script to Wordpress before you can use $wpdb.

The usual way to do this is to include wp-blog-header.php:

 include "/path/to/wordpress/wp-blog-header.php";
9
  • Thanks a lot. But is there an alternative to /path/to/wordpress/ ? Now my path to wordpress is C://xampp/htdocs/new/ and I don't want to use it that way.
    – zuzuleinen
    Commented Aug 31, 2011 at 7:32
  • @zuzuleinen if you're in the same directory with this script, you don't need to use the path. wp-blog-header.php alone will do then
    – Pekka
    Commented Aug 31, 2011 at 7:33
  • I'm not in the same directory, I am in my theme directory. Should I copy wp-blog-header.php in my theme files or there's a more elegant way to do this?
    – zuzuleinen
    Commented Aug 31, 2011 at 7:35
  • 1
    @zuzuleinen you can use relative paths, e.g. ../../../wp-blog-header.php Do not copy the header file, it won't work
    – Pekka
    Commented Aug 31, 2011 at 7:36
  • 2
    if you want it to work in all cases (you could suddenly decide you want to have subdirectories in your theme etc...), you can also get the wp-header-file like this: get_option('home') . "/wp-blog-header.php"; this will always work. Commented Aug 31, 2011 at 8:14
3

Before you can use wpdb class:

global $wpdb;
1
  • exactly, you need to call the global wpdb varaible by using global $wpdb;
    – moffepoffe
    Commented Aug 31, 2011 at 11:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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