global variables in wordpress or woocommerce - php

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.

Related

Wordpress Functions.php filter get_metadata is always empty

I have a post and I need to process some of the meta data attached to that post.
I am struggling to get the post meta when calling get_metadata('post',53 ) where 53 is the specific postid I need.
The write_log function outputs to my debug log and the return value is always empty.
add_filter( 'facetwp_indexer_row_data', function( $rows, $params ) {
if ( 'company_categories' == $params['facet']['name'] ) {
write_log($params); //params contains correct values
$defaults = $params['defaults'];
$post_id = (int) $defaults['post_id'];
$post = get_post($post_id);
$postType = $post->post_type;
write_log($postType." - ".$post_id); //postType and post_id contains correct values
//global $post;
if($postType == 'upt_user'){
$meta = get_metadata('post',$post_id );
write_log($meta); //meta is empty when using both $post_id variable and actual id value '53'
}
}
return $rows;
}, 999, 2 );
If I add the exact same code to a php template it returns the metadata without issue.
e.g.
$meta = get_metadata('post',53 );
I actually started with the get_post_meta function but I'm currently using get_metadata to simplify and rule out any issues with misusing the get_post_meta function and parameters.
Any suggestions of how to resolve please?

Simple shortcode woes, coding for dummies

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"]

increase index in wordpress plugin

I try to make shortcode plugin which display number of my shortcodes.
<?php
$numberOfShortcodes = 0;
function ppndr_shortcode( $atts ){
$numberOfShortcodes++;
return $numberOfShortcodes;
}
add_shortcode( 'countdown', 'ppndr_shortcode' );
?>
When i add two shortcodes it display "11". How to increase numberOfShortcodes?
Use global keyword:
<?php
$numberOfShortcodes = 0;
function ppndr_shortcode( $atts ){
global $numberOfShortcodes;
$numberOfShortcodes++;
return $numberOfShortcodes;
}
add_shortcode( 'countdown', 'ppndr_shortcode' );
?>
Why? You are trying to get value of global variable $numberOfShortcodes, but server thinks you want the local (from function scope), which is not set, so creates new one. If you use global, php will know, you mean the global variable and will use it.

Getting post id on send_headers action in WordPress

Is it possible in WordPress to get ID of current post in send_headers hook? global $post and $wp_query doesn't work or i did something wrong.
class myClass {
public function __construct() {
add_action('send_headers', array($this, 'myFunction'));
}
public function myFunction() {
// need to get post ID here
}
It looks like WordPress hasn't gotten to the point of initiating $wp_query when the action send_headers is triggered.
As the question asks how to get the post ID this answer assumes that you have the slug in the url instead. If the slug is the last part of the url then this will get the post ID for you.
$post = get_posts ( array (
'name' => pathinfo ( $_SERVER['REQUEST_URI'] )['filename']
) )[0];
echo $post->ID;
This result will need to be tested per use, but should work for most purposes.
You even can try something like this:
global $wp;
$post = get_page_by_path($wp->request);
echo $post->ID;

Preserving postdata with embedded wp_query queries?

I'm designing a website in Wordpress. This site is one of those parallax sites where all the pages are printed on the homepage and the menu scrolls to the anchors.
That being said I am using a wp_query to pull out all the pages that are in the main menu. Furthermore I have a shortcode that I use in the content that also requires the use of wp_query.
The problem I have is that the shortcode (the embedded wp_query) is screwing up the postdata. I know when using wp_query you'd usually want to use wp_reset_postdata but in this particular situation it doesn't work because this function call will restore the postdata of the homepage and not of the currently running wp_query (sorry if I'm being unclear).
Is there a way to take a snapshot of the postdata to then restore after my shortcode? I'm looking for something along the lines of:
function my_shortcode() {
save_postdata(); //saves the current postdata
$query = new WP_Query();
while( $query->have_posts() ) {
$query->the_post();
echo get_the_title();
}
my_wp_reset_postdata(); //restores the postdata to where it was before the loop
}
By looking in the source for wp_reset_query(), you will see that what it does is that it simply restores the $wp_query global variable from another global variable($wp_the_query - this is set-up together with the initial set-up for $wp_query, so it holds the original query).
What you can do is you can simply assign $wp_query to a different global variable and then later restore it. Here's an example:
function _save_query( $var = '_wp_query' ) {
$GLOBALS[ $var ] = $GLOBALS['wp_query'];
}
function _wp_reset_query( $var = '_wp_query' ) {
$GLOBALS['wp_query'] = $GLOBALS[ $var ];
wp_reset_postdata();
}
So simply call _save_query() before overwriting the query(you can pass a custom variable name - this way you can store multiple WP_Query objects :) ).
Once you want to restore the query data, call _wp_reset_query() - again you can pass a string as a variable name in order to restore this exact query object.
This is how I managed to get it working, credit goes to Nikola's question since I worked off of his idea.
function _save_query( $var = '_wp_query' ) {
global $post;
$GLOBALS[ $var ] = $post;
}
function _wp_reset_query( $var = '_wp_query' ) {
global $post;
$post = $GLOBALS[ $var ];
setup_postdata( $post );
}
I looked at the documentation of how the loop works found here. I decided to use the same kind of setup as in Nikola's answer since it met my criteria but I used the implementation of the_post to restore the postdata. This is probably not very efficient since it's using the setup_postdata function (which I assume is overkill) but it has definitely solved my problem.
So now when I embed a wp_query I can just do the following:
_save_query();
$products = new WP_Query( $args );
if( $products->have_posts() ) {
$ob .= '<ul class="group-posts">';
while ( $products->have_posts() ) {
$products->the_post();
$ob .= '<li>'.get_the_title().'</li>';
}
_wp_reset_query();
$ob .= '</ul>';
}
Side question/note: What's the etiquette for marking an answer as the correct answer? I'd feel bad accepting my answer as the correct one when Nikola helped me reach it?
my_wp_reset_postdatadoes not exist. You have to use wp_reset_postdata(). But in a situation where you have to chain multiple wp_queries and come back to the older ones, you can store your first query in a variable, set the new WP_query, then reset it and come back to the old one.
$wp_query stores the current loop. So you can go something like :
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query($args);
...
// then later
$wp_query = $temp;
// And back on tracks !

Categories