Brad Fletcher
Brad Fletcher

Reputation: 3593

Variable via GET not working in wordpress

I am carrying a variable via $_GET to a page which processes the action, the variable carries over correctly but the database won't update and throws an error.

Here is my link with a varible;

echo "<td><a href='".plugins_url()."/myremovalsquote/inc/disable.php?id=".$active_partner->partner_id."' class='button-primary'>Disable</a></td>";

I then use the variable passed in my /disable.php

$id = $_GET['id'];

echo $id;

global $wpdb;

if ($commit = $wpdb->query("UPDATE partners SET active='no' WHERE partner_id='"'$id'"'")) {
	echo 'Success';
} else {
	echo 'Failed';
}

The echo outputs the correct string, but then I get this error message.

77
Fatal error: Call to a member function query() on a non-object in /home/myremovalsquote/public_html/wp-content/plugins/myremovalsquote/inc/disable.php on line 9

Upvotes: 0

Views: 1138

Answers (1)

doublesharp
doublesharp

Reputation: 27667

You are calling a PHP file directly without loading WordPress, so $wpdb and it's method aren't available to you.

You can fix this by including wp-load.php, however this is generally considered to be bad form, as explained in Don't include wp-load please.

A better solution would be to create an AJAX listener, and then call that from your link (it doesn't really have to be a JavaScript request or JSON response). You would need to pass in your action to call the right PHP method, along with your other variables.

// attach action "handler_33762965" to the handler_33762965() function for admin (wp_ajax_*) and front end (wp_ajax_nopriv_*)
add_action( 'wp_ajax_handler_33762965', 'handler_33762965' );
add_action( 'wp_ajax_norpriv_handler_33762965', 'handler_33762965' );
function handler_33762965(){
    // make sure the ID is set before grabbing it
    $id = isset( $_GET['id'] )? $_GET['id'] : 0;
    // do stuff
    exit();
}

Your link would look like the following.

<a href="/wp-load.php?action=handler_33762965&id=<?php echo $id; ?>">link</a>

Upvotes: 1

Related Questions