This is the code in bd-custom.php
global $bp_profile_field_data;
function show_profile_field()
{
$args = array(
'field' => 'Field Name',
'user_id' => 1
);
$tx_profile_field = bp_profile_field_data( $args );
};
but i want to use this string in a plugin but it echo empty space
you get the string from the database
$matric = $wpdb->get_row("SELECT value FROM wp_bp_xprofile_data WHERE field_id = 2 AND user_id = 3");
// this variable holds the string
$matric->value
Related
I'm creating a user and I want to add a metadata "Age" numeric.
The problem is that when I add it, it adds it as string
$user_id = wp_insert_user( array(
'user_login' => 'janedoe',
'user_pass' => 'passwordgoeshere',
));
add_user_meta($user_id, 'Age' , 20);
wp_set_current_user($user_id);
var_dump(get_user_meta( get_current_user_id(),"Age"));
This is the result
Array (1) {
[0] =>
String (2) "20"
}
Why do not you pick it up as int?
Thanks
add_user_meta( int $user_id, string $meta_key, mixed $meta_value, bool $unique = false )
$meta_value is mixed type to save all variable types, it doesn't know when the value is an integer or a string. So basically, it will convert/sanitize all variables to string.
You can find out more at https://developer.wordpress.org/reference/functions/add_user_meta/
Hyy
Try this,
$user_id = wp_insert_user( array(
'user_login' => 'janedoe',
'user_pass' => 'passwordgoeshere',
));
add_user_meta($user_id, 'Age' , 20);
wp_set_current_user($user_id);
$usertest = get_user_meta( get_current_user_id(),"Age", true);
$int = (int)$usertest;
var_dump($int);
I have a product attribute variation which has options of -
small - $20
medium - $25
large - $30
Since all the products in the store has the same price for this variations.
How to set the price for the attribute values programmatically?
3 attribute variation buttons are show on product page when I add them as variations.
How to change the price of product when "small" option is selected programmatically instead of setting price in variation options in admin panel.
As Per our understanding to want to add products with different sizes and different prices.
There is 2 way:
1. You can add from woocommerece dashboard like this:
https://www.ostraining.com/blog/woocommerce/product-variations/
You can add programmatically like this:
function insert_product ($product_data)
{
$post = array( // Set up the basic post data to insert for our product
'post_author' => 1,
'post_content' => $product_data['description'],
'post_status' => 'publish',
'post_title' => $product_data['name'],
'post_parent' => '',
'post_type' => 'product'
);
$post_id = wp_insert_post($post); // Insert the post returning the new post id
if (!$post_id) // If there is no post id something has gone wrong so don't proceed
{
return false;
}
update_post_meta($post_id, '_sku', $product_data['sku']); // Set its SKU
update_post_meta( $post_id,'_visibility','visible'); // Set the product to visible, if not it won't show on the front end
wp_set_object_terms($post_id, $product_data['categories'], 'product_cat'); // Set up its categories
wp_set_object_terms($post_id, 'variable', 'product_type'); // Set it to a variable product type
insert_product_attributes($post_id, $product_data['available_attributes'], $product_data['variations']); // Add attributes passing the new post id, attributes & variations
insert_product_variations($post_id, $product_data['variations']); // Insert variations passing the new post id & variations
}
function insert_product_attributes ($post_id, $available_attributes, $variations)
{
foreach ($available_attributes as $attribute) // Go through each attribute
{
$values = array(); // Set up an array to store the current attributes values.
foreach ($variations as $variation) // Loop each variation in the file
{
$attribute_keys = array_keys($variation['attributes']); // Get the keys for the current variations attributes
foreach ($attribute_keys as $key) // Loop through each key
{
if ($key === $attribute) // If this attributes key is the top level attribute add the value to the $values array
{
$values[] = $variation['attributes'][$key];
}
}
}
$values = array_unique($values); // Filter out duplicate values
wp_set_object_terms($post_id, $values, 'pa_' . $attribute);
}
$product_attributes_data = array(); // Setup array to hold our product attributes data
foreach ($available_attributes as $attribute) // Loop round each attribute
{
$product_attributes_data['pa_'.$attribute] = array( // Set this attributes array to a key to using the prefix 'pa'
'name' => 'pa_'.$attribute,
'value' => '',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
);
}
update_post_meta($post_id, '_product_attributes', $product_attributes_data); // Attach the above array to the new posts meta data key '_product_attributes'
}
function insert_product_variations ($post_id, $variations)
{
foreach ($variations as $index => $variation)
{
$variation_post = array( // Setup the post data for the variation
'post_title' => 'Variation #'.$index.' of '.count($variations).' for product#'. $post_id,
'post_name' => 'product-'.$post_id.'-variation-'.$index,
'post_status' => 'publish',
'post_parent' => $post_id,
'post_type' => 'product_variation',
'guid' => home_url() . '/?product_variation=product-' . $post_id . '-variation-' . $index
);
$variation_post_id = wp_insert_post($variation_post); // Insert the variation
foreach ($variation['attributes'] as $attribute => $value) // Loop through the variations attributes
{
$attribute_term = get_term_by('name', $value, 'pa_'.$attribute); // We need to insert the slug not the name into the variation post meta
update_post_meta($variation_post_id, 'attribute_pa_'.$attribute, $attribute_term->slug);
}
update_post_meta($variation_post_id, '_price', $variation['price']);
update_post_meta($variation_post_id, '_regular_price', $variation['price']);
}
}
function insert_products ($products)
{
if (!empty($products)) // No point proceeding if there are no products
{
array_map('insert_product', $products); // Run 'insert_product' function from above for each product
}
}
$json = file_get_contents('product-data.json'); // Get json from sample file
// $products_data = json_decode($json_file, true); // Decode it into an array
echo json_last_error();
// if(get_magic_quotes_gpc()){
// $d = stripslashes($json);
// }else{
// $d = $json;
// }
$d = json_decode($d,true);
$products_data = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json), true );
echo "<h1>json</h1>";
echo "<pre>";
print_r($json);
echo "</pre>";
echo "<h1>Product data</h1>";
echo "<pre>";
var_dump($products_data);
echo "</pre>";
insert_products($products_data);
Where $product_data sample:
$product_data = array(
'sku' => '123SKU',
'categories' => array('size', 'color'),
'available_attributes' => array('size', 'color'),
'variations' => array(
'size' => array(
'attributes' => array( 'XL', 'M', 'S' ),
),
'color' => array(
'attributes' => array( 'Blue', 'Red', 'Green' )
)
)
)
insert_products($products_data);
Note: You can create product-data.json and import product or you can create $product_data = (); and set on insert_products() function.
For Aditional Info:
You can also check this URL for more info https://newbedev.com/create-programmatically-a-woocommerce-product-variation-with-new-attribute-values
I am getting an error with WordPress wp_update_post() function that says "Invalid post ID". Here is my code:
$current_item = 273;
$my_post = array(
'ID' => $current_item,
'post_title' => 'This is the post title.',
'post_content' => 'This is the updated content.',
);
$post_id = wp_update_post( $my_post, true );
if (is_wp_error($post_id)) {
$errors = $post_id->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
Thanks in advance .
Use 'import_id', not 'ID'.
If there is no post at the ID you specify, wp_update_post() doesn't create a new one - it returns an error. In order to specify the ID of a new post use 'import_id' => $current_item.
Note, though, that if there IS a post with that ID, import_id will cause a new post instead of an update. So if you want to EITHER make a new post with that ID OR update the post at that ID, you'll need an if statement to pick your key:
$newPostKey = (get_post_status($current_item)) ? 'ID' : 'import_id';
// If there's a post with an ID of $current_item, we'll use 'ID'.
// Otherwise, use 'import_id'.
Here's your shiny new code.
$current_item = 273;
$newPostKey = (get_post_status($current_item)) ? 'ID' : 'import_id';
$my_post = array(
$newPostKey => $current_item,
'post_title' => 'This is the post title.',
'post_content' => 'This is the updated content.',
);
$post_id = wp_update_post( $my_post, true );
Not sure where the problem is in the following form used in a template file in Drupal7. Help is highly appreciated. The problems are the following:
1. The variables $title and $surname are not passed over to the form's default value.
=> Error Message: Notice: Undefined variable: title in form_user_information()
=> Error Message: Notice: Undefined variable: surname in form_user_information()
2. There's a Warning: strpos() expects parameter 1 to be string, array given in drupal_strip_dangerous_protocols()
Thanks in advance.
<?php
//Load User data:
global $user;
$uid = $user->uid;
$account = user_load($uid);
//Get User data:
$title = 'Mrs.';
print $title . '<br><br>'; //Result: Value is printed and not empty!
$surname = check_plain($account->field_vorname['und']['0']['value']);
//$surname = 'Tom';
print $surname . '<br><br>'; //Result: Both values are printed and are not empty!
function form_user_information($form, &$form_state) {
//Form
$form['#action'][] = request_uri();
$form['#id'][] = 'form_user_information';
$form['#validate'][] = 'form_user_information_validators';
$form['#submit'][] = 'form_user_information_submit';
$form['#prefix'] = '<div id="form_user_information">';
$form['#suffix'] = '</div>';
//Select-Field: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#select
$form['Title'] = array(
'#type' => 'select',
'#title' => t('Title'),
'#options' => array(
'Frau' => t('Mr.'),
'Herr' => t('Mrs.'),
),
'#default_value' => $title,
);
$form['surname'] = array(
'#type' => 'textfield',
'#maxlength' => 50,
'#size' => 40,
'#required' => TRUE,
'#title' => t('Surname'),
//'#attributes' => array('placeholder' => $surname),
'#default_value' => $surname,
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => 'Confirm data');
return $form;
}
//print form
$form = drupal_get_form('form_user_information');
print drupal_render($form);
//Form Validation:
function form_user_information_validators($form, &$form_state) {
if ($form_state['values']['surname'] == '') {
form_set_error('surname', t('Please enter your surname.'));
}
}
//Form Submit:
function form_user_information_submit($form, &$form_state) {
//...
}
//get form information
echo "<pre>".print_r($form,true)."</pre>";
?>
1) Set the global variables $title and $surname with global scope:
//Get User data:
$global $title = ...
$global $surname = ...
Otherwise set all these variables (including $user) inside the function form_user_information which is the best practice.
I would also suggest not use $title as variable name because it may cause problems with already defined $title of the $page variable. Instead use something like $user_title.
2) Which line does this come from?
Guess this issue can be closed. See the 2 comments. Thanks Theodoros for your help.
I'm trying to get all the comments from a post by an array of users.
This is what I'd like to be able to do:
$user_ids = array(10, 22, 41, 80);
$post_id = 57;
$args = array (
'number' => -1,
'user_id' => $user_ids,
'post_id' => $post_id,
'status' => 'approve',
'order' => 'DESC'
);
$comments = get_comments( $args );
Now obviously this doesn't work, but that's what I'd like to do. Is there any other way to achieve this? Maybe using a custom select?
I've built a WPDB query based on the query method of WP_Comment_Query class. And doing the sanitization based on this forum post.
global $wpdb;
// Sanitize
$post = '1148';
$post = absint($post);
// Sanitize
$a = '2'; // User One
$b = '3'; // User Two
$user_ids = array_map( 'absint', array( $a, $b ) );
$user_ids = implode( ', ', $user_ids );
$query = "SELECT * FROM $wpdb->comments
WHERE comment_post_ID = $post
AND user_id IN ($user_ids)
AND comment_approved = 1
ORDER BY comment_date DESC";
$comments = $wpdb->get_results( $query );
A simple SELECT query would do:
$query = "SELECT * FROM $wpdb->comments
WHERE comment_post_ID = %d
AND comment_approved = 1
AND user_id IN %s
ORDER BY comment_date DESC"; // get only approved comment and sort by date
$comments = $wpdb->get_results($wpdb->prepare(
$query,
intval($post_id),
'('.implode(',', array_map('intval', $user_ids)).')'
)); // use prepare to prevent SQL injection
Hope this helps.
We can use the OR condition in MySQL to do this.
If I was to write the query we want using the values you provided it could be done something like this:
SELECT * FROM comments WHERE comment_post_ID='57' AND (user_id='10' OR user_id='22' OR user_id='41' OR user_id='80')
Now, we can make this dynamic and processable by PHP:
// The User IDs and Post ID (make sure you are escaping these properly).
$user_ids = array(10, 22, 41, 80);
$post_id = 57;
foreach($user_ids as $uid){ $user_ids_string .= " OR user_id='$uid'"; } // Loop through each user and append their ID to the query segment.
$user_ids_string = substr($use, 4); // Remove the unnecessary first " OR "
$query = mysql_query("SELECT * FROM comments WHERE comment_post_ID='$post_id' AND ($user_ids_string)"); // Create the final MySQL Query.
while($row = mysql_fetch_array($query)){
// Do something with each $row[].
}
Before you use this, make sure you're connected to the WordPress database properly before using this and that all the tables and fields I've listed are correct for your installation first.
paste this code in functions.php
function users_comment( $postid = null , $users = array() ){
if( ! empty( $users ) && $postid ){
foreach ($users as $user) {
$args = array (
'number' => '',
'user_id' => $user,
'post_id' => $postid,
'status' => 'approve',
'order' => 'DESC'
);
$comments[] = get_comments( $args );
}
return $comments;
}else{
return 'Please provide a user id and postid';
}
}
use this function anywhere you want by calling it required parameters user ids and post id.
print_r( users_comment(1,array(1,4,3)) );
only single user to get post:
$args = array(
'status' => 'approve',
'number' => '-1',
'post_id' => 57,
'user_id' => 1,
'order' => 'DESC'
);
$comments = get_comments($args);
foreach($comments as $comment) :
echo($comment->comment_author . '<br />' . $comment->comment_content);
endforeach;
?>
For multiple user get comment using post id:
$args = array( 'user_id' => 0 );
add_filter( 'comments_clauses', 'custom_comments_clauses');
$comments = get_comments( $args );
remove_filter( 'comments_clauses', 'custom_comments_clauses');
function custom_comments_clauses( $clauses ){
$clauses['where'] = str_replace( 'user_id = 0',
'user_id IN (1, 2, 3)',
$clauses['where'] );
return $clauses;
}
https://wordpress.stackexchange.com/questions/105010/get-comments-only-for-certain-specific-users-in-template-file
As Brasofilo already provided you the custom query to get the comments but it will fetch all the comments while they were trashed
$user_ids = array(10, 22, 41, 80);
$post_id = 57;
global $wpdb;
$comments=$wpdb->get_results("SELECT * FROM `wp_comments` WHERE
`comment_post_ID` =$post_id AND `user_id` IN (".join(',',$user_ids)")
AND `comment_approved` ='1' ORDER BY `comment_date` DESC");