0

I am working with a Wordpress site and have created a custom page in /home/planmyme/public_html/php/ with the name response.php. On this page I am getting a value to insert in the wp_postmeta table (value examples: transaction ID, purchase ID, order ID, or item name), but I am not able to insert it.

I am using the code below as a test. I do not understand how to achieve this, or if there is any need of a database connection to run the query.

$metakey    = "_menu_item_type";
$metavalue  = "WordPress' database interface is like Sunday Morning: Easy.";

$wpdb->query( $wpdb->prepare( 
    "
        INSERT INTO $wpdb->wp_postmeta
        ( post_id, meta_key, meta_value )
        VALUES ( %d, %s, %s )
    ", 
    10, 
    $metakey, 
    $metavalue 
) );

Getting this error

Fatal error: Call to a member function query() on a non-object in /home/planmyme/public_html/php/response.php on line 56

If anybody has an idea how to do this, please let me know.

  • 1
    I'm sure this is a duplicate. Try to search for WP_USE_THEMES on this site to find out how to include WordPress in an external script. But why don't you include your script directly into WordPress via plugin or a page template? – birgire Jun 30 '14 at 14:07
  • 1
    Have you defined "global $wpdb;" in your function ? – WisdmLabs Sep 2 '14 at 5:44
1

The error message basically says that $wpdb is not an object so you can't call any methods on it. As we can't see where $wpdb is defined in the source you posted it's hard to tell any further details.

Are you even including wordpress in your external file? You need to require wp-load.php to use the wordpress functions and classes in an external application.

0

At the moment, your PHP file doesn't recognize $wpdb object.

To utilize WordPress functions within your PHP file, you should first add WordPress support by adding below to the top of your file:

<?php require('/the/path/to/your/wp-blog-header.php'); ?>

Then you can use $wpdb - after defining it:

<?php global $wpdb; ?>

Finally, you should use either the table prefix specifically or let $wpdb do it for you. Later is preferred so a change in table prefix won't affect your PHP file. Hence your SQL should be changed to:

INSERT INTO $wpdb->postmeta

..instead of $wpdb->wp_postmeta

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.