Hey guys so I am trying to access my database which is within wordpress to get some field values and I tried doing just straight up PDO style but it seems to not work so I went into wordpress codex and did their way to call things, but still no success!
CODE:
/***GET USERNAME***/
global $current_user;
get_currentuserinfo();
$accusername = $current_user->user_login ;
/******SEE IF FIRST TIME DISCOUNT CODE BEEN USED*******/
$wpdb->query(
$wpdb->prepare(
"
SELECT firsttime_discount
FROM $wpdb->users
WHERE user-login = %d
",
$accusername
)
);
/******CHECK IT******/
echo"working";
$wpdb->query('query');
echo"working";
if ($checkFTDiscount->firsttimediscount != 1){
$validFTDiscount = 1;
}
else{
$validFTDiscount = 0;
echo"wori";
}
So it's suppose to go in and see if the value for discount code is set to 1 in the wp_user area, and if not just set a value to 0.
Let me know if you have any other questions.
Before you can use $wpdb, you must declare global $wpdb;
global $current_user, $wpdb;
Should do the trick.
Related
been asked to help a friend display some custom data on a Wordpress site, easy I thought...
Have a table with customer data in. Idea a plugin to is to query the table based on current user id and spit it out as shortcodes so they can place the output where ever they like.
After much googling (I'm not a coder) I got something that worked! Problem is, even to my untrained eye, it looks like a bodge, repeating queries when there's clearly a more intelligent way of doing it.... Can someone clever please show me the way based on the this >> ?
<?php
Plugin Name: do stuff
Description: Do site specific stuff
function spend_data() {
global $wpdb;
global $current_user;
wp_get_current_user();
$userid = $current_user->ID;
$spend = $wpdb->get_var ( "SELECT spend FROM mytable WHERE the_id=$userid");
return $spend;
}
function detail_data() {
global $wpdb;
global $current_user;
wp_get_current_user();
$userid = $current_user->ID;
$detail = $wpdb->get_var ( "SELECT detail FROM mytable WHERE the_id=$userid");
return $programs;
}
add_shortcode('spend', 'spend_data');
add_shortcode('detail', 'detail_data');
/* Stop Adding Functions Below this Line */
I guess you could do a query for all fields at a hook that fires before the shortcodes and then store it all in $current_user. Don't forget to replace mytable with the correct tablename.
function marks_prepare_user_shortcodes () {
global $wpdb;
global $current_user;
$current_user = wp_get_current_user();
$userid = $current_user->ID;
$row = $wpdb->get_row( "SELECT * FROM mytable WHERE the_id=".$userid, ARRAY_A);
$current_user->marks_shortcodes = $row;
}
add_action( 'wp_head', 'marks_prepare_user_shortcodes');
And then your shortcodes change to
function spend_data() {
global $current_user;
$spend = $current_user->marks_shortcodes['spend'];
if (!is_null($spend))
return $spend;
}
function detail_data() {
global $current_user;
$detail = $current_user->marks_shortcodes['detail'];
if (!is_null($detail))
return $detail;
}
add_shortcode('spend', 'spend_data');
add_shortcode('detail', 'detail_data');
I'm not sure if wp_head is the correct /best action to pick here, you could give it a try. I figured it is called before all the shortcodes are. Code is untested.
Ps. As a sidenote, I believe your extra user data should actually be stored in the wp_usermeta table, instead of a separate table. You'd retrieve the fields with get_user_meta(): https://developer.wordpress.org/reference/functions/get_user_meta/
Update
Instead of the code block directly above, you could also use this:
function mikes_data_shortcode($atts) {
global $current_user;
$atts = array_change_key_case((array)$atts, CASE_LOWER);
// override default attributes with user attributes
$actual_atts = shortcode_atts([
'field' => 'YouDidntEnterAFieldNameAsAttribute',
], $atts);
$data = $current_user->marks_shortcodes[$actual_atts['field']];
if (!is_null($data))
return $data;
}
function mikes_shortcodes_init()
{
add_shortcode('mikes_data_shortcode', 'mikes_data_shortcode');
}
add_action('init', 'mikes_shortcodes_init');
Where you use shortcodes like this:
[mikes_data_shortcode field="spend"]
or
[mikes_data_shortcode field="detail"]
I'm currently building a site for a client and they want a search feature that will search all of the products they supply.
I have created a new table in the database called sc_products and then tried the below code in a wordpress template page but I don't appear to be getting anywhere. If anyone knows how I can get this working that would be awesome!
<?php
/*
Template Name: myTemp
*/
function search_it() {
if ( is_search() && isset($_GET['s'])) {
global $wpdb;
$address_table = $wpdb->prefix . "sc_products";
$myrows = $wpdb->get_results( 'SELECT product FROM ' . $sc_products );
foreach ( $myrows as $single_row ) {
global $single_row;
}
$product = $single_row->product;
}
return $product;
}
$city = search_it();
echo $city;
get_search_form();
?>
There's a couple of things going on here, let's see if we can work them out.
Here's your modified function which should perform a search, with comments throughout to help explain what's going on.
NOTES:
1. You declare $address_table, but then use $sc_products. That can't be correct, as $sc_products is not defined.
2. This answer is based on the column names you provided in comments - IF they are not an exact match, you'll need to update them, INCLUDING matching case. If it's not Application, but instead application, you'll need to make that change.
function search_it() {
// If this is a search, and the search variable is set
if ( is_search() && isset( $_GET['s'] ) ) {
// Global in $wpdb so we can run a query
global $wpdb;
// Build the table name - glue the table prefix onto the front of the table name of "sc_products"
$address_table = $wpdb->prefix . "sc_products";
// Get the search term into a variable for convenience
$search = $_GET['s'];
// To use "LIKE" with the wildcards (%), we have to do some funny business:
$search = "%{$search}%";
// Build the where clause using $wpdb->prepare to prevent SQL injection attacks
// Searching ALL THREE of our columns: Product, Application, Sector
$where = $wpdb->prepare( 'WHERE Product LIKE %s OR Application LIKE %s OR Sector LIKE %s', $search, $search, $search );
// Execute the query with our WHERE clause
// NOTE: Your code originally used "$sc_products", but that variable was not defined - so have replaced to the proper $address_table here.
$results = $wpdb->get_results( "SELECT product FROM {$address_table} {$where}" );
// return the results. No need to put into an array, it's already an array
return $product;
}
// For consistency, return an empty array if not a search / no search term
return array();
}
// USAGE:
// Run the query
$cities = search_it();
// You can't echo an array!
// echo $city;
// var_dump to see the whole array
var_dump( $cities );
// More useful USAGE:
$cities = search_it();
// If there's any results
if ( ! empty( $cities ) ) {
// Output a title
echo '<h1>Product Search Results:</h1>';
// Loop over the results
foreach( $cities AS $city ) {
// $wpdb returns an array of objects, so output the object properties
echo '<h2>' . $city->Product . '</h2>';
echo '<p>' . $city->Application . '</p>';
echo '<p>' . $city->Sector . '</p>';
}
}
get_search_form();
public function action_save_post($post_id) {
global $wpdb;
$wooqty = $_POST['qty'];
if( !empty( $wooqty ) )
update_post_meta( $post_id, 'qty', esc_attr( $wooqty ) );
}
This will save the data from a Form field in Metabox in wordpess. I would like to use this variable $wooqty which has a value to another function.
public function action_woocommerce_add_order_item_meta($item_id, $values) {
global $wpdb;
$product_no = (int) $values['product_id'];
$qty_no = (int) $values['quantity'];
}
I would like to replace the variable $qty_no data to the $wooqty. my problem is how do i pass the variable $wooqty to this function so that i can replace the values of $qty_no.
Seems simple enough to me. You don't need to set a global, since it is already in Wordpress post meta data. Just call get_post_meta($product_no, 'qty', TRUE); within the function.
So, your new function will look like this:
public function action_woocommerce_add_order_item_meta($item_id, $values) {
global $wpdb;
$product_no = (int) $values['product_id'];
$qty_no = get_post_meta($product_no, 'qty', TRUE);
}
Not sure why you are globalizing $wpdb, since the function doesn't do any database operations using that variable. You should be fine with removing the global $wpdb; definition at the top of your function as well.
Furthermore, I would check $item_id variable and see if that is equal to $values['product_id'], and if it is, use that instead of refetching the product id from the $values array.
Hope I helped, if not be clearer in your question. Question seems a bit old, so you probably already got this figured out by now. But just in case you haven't.
so you can use the following syntax to set the global from within a function and then access it elsewhere in PHP.
function foo(){
$GLOBALS['foobar'] = 'somestring';
}
function bar(){
echo $GLOBALS['foobar'];
}
foo();
bar();
However, it's not often a good idea and there may be a better way to pass the variable to the functions. How about a third function that sets the variable locally that's called from within functions 1 and 2 for instance.
I am trying to write a simple plugin that, among other things, creates a custom post type.
I have been searching everywhere but I have really no idea on how to write the uninstall function that delete the custom post type and all its entries from the db.
I have found this on the WordPress codex, but I don't understand what to do with it.. shame
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) )
exit();
$option_name = 'plugin_option_name';
delete_option( $option_name );
// For site options in multisite
delete_site_option( $option_name );
//drop a custom db table
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytable" );
Can anyone help?
Thanks in advance
Would this be correct?
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) )
exit();
global $wpdb;
$posts_table = $wpdb->posts;
$query = "
DELETE FROM wp_posts
WHERE post_type = 'messages'
";
$wpdb->query($query);
The WP codex page http://codex.wordpress.org/Function_Reference/register_uninstall_hook has 2 important pieces of information, only 1 of which you list in your question. You do need to make sure that you register the hook.
That aside, if you want to remove all custom post data (regardless if it is upon uninstallation or as another person commented having a seperate button to remove data as many plugins do) you need to be sure to remove the postmeta records as well.
global $wpdb;
$cptName = 'messages';
$tablePostMeta = $wpdb->prefix . 'postmeta';
$tablePosts = $wpdb->prefix . 'posts';
$postMetaDeleteQuery = "DELETE FROM $tablePostMeta".
" WHERE post_id IN".
" (SELECT id FROM $tablePosts WHERE post_type='$cptName'";
$postDeleteQuery = "DELETE FROM $tablePosts WHERE post_type='$cptName'";
$wpdb->query($postMetaDeleteQuery);
$wpdb->query($postDeleteQuery);
What php code can be used to retrieve the current page ID in a Wordpress theme? Then pull the booking_type_id from the database that is linked to that ID.
I have tried so many different things and I just cant seem to get it to work.
I am trying to use something along the lines of
<?php
$bookingid = $wpdb->get_var("SELECT booking_type_id FROM hobookingtypes WHERE post_id = 'the_ID();' ");
// Echo the booking resource id
echo $bookingid;
?>
But I am really not sure what I am doing wrong.
You can't use the_ID() because its echo the POST_ID, so use the global object $post the provide all the information related to post;
global $post;
$bookingid = $wpdb->get_var(
"SELECT booking_type_id FROM hobookingtypes
WHERE
post_id = '". $post->ID ."'"
);
// Echo the booking resource id
echo $bookingid;
Alternative of global $post:
OR you can use get_the_ID() instead of the_ID()
You can get current post ID with this code,
global $post;
$id = $post->ID;
or just,
global $post_id;
$id = $post_id;
or you can use,
get_the_ID() function insted.