I can't find a solution or right example for something that should be quite simple: assign a role to an user when creating it, this is what I'm trying:
$edit = array(
'name' => $_POST['name'],
'pass' => $password,
'mail' => $_POST['email'],
'status' => 0,
'language' => 'es',
'init' => $_POST['email'],
array(2 =>'authenticated', 4=>'my custom role') //as id and named in role db table
);
user_save(NULL, $edit);
The user is not being created, how can I do this?
Thank you
You haven't named the roles member as such. Try his modified version:
$edit = array(
'name' => $_POST['name'],
'pass' => $password,
'mail' => $_POST['email'],
'status' => 0,
'language' => 'es',
'init' => $_POST['email'],
'roles' => array(
2 => 'authenticated',
4 => 'my custom role',
),
);
user_save(NULL, $edit);
And you can use objects to do that.
// Check if user's email is unique
if (!user_load_by_mail($_POST['email'])) {
$account = new stdClass;
$account->name = $_POST['name'];
$account->pass = user_hash_password($password);
$account->mail = $_POST['email'];
$account->status = FALSE;
$account->language = 'es';
$account->init = $_POST['email'];
$account->roles = array(
DRUPAL_AUTHENTICATED_RID => TRUE,
'Your custom role' => TRUE,
);
user_save($account);
}
Here is a hook I've written to add a role to a user when a new user is inserted:
<?php
function MYMODULE_user_insert(&$edit, $account, $category){
if (array_key_exists('profile_1', $account)) {
$is_university = FALSE;
if ($account->profile_sport_club['field_club']['und'][0]['value'] == 1 ) {
$is_university = TRUE;
}
if ($is_university) {
$uid = $account->uid;
$role_name = 'uni_club';
if ($role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(array($uid), 'add_role', $role->rid);
}
}
}
}
?>
Thanks to this tip, it's now much simpler.
function first_user_insert(&$edit, $account, $category, $node){
$uid = $account->uid;
$role_name = 'role name';
if ($role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(array($uid), 'add_role', $role->rid);
}
}
Related
I want to add a new attribute to an existing woocommerce product. I use this code
$pf = new WC_Product_Factory();
$product = $pf->get_product(76);
//Create the attribute object
$attribute = new WC_Product_Attribute();
$attribute->set_id( 0 );
//pa_color slug
$attribute->set_name( 'color' );
//Set terms slugs
$attribute->set_options( array(
'blue',
) );
$attribute->set_position( 0 );
//If enabled
$attribute->set_visible( 1 );
$product->set_attributes(array($attribute));
$id = $product->save();
this code working fine but I want to add attributes with terms, this code create custom product attribute.
I want to create attribute like this image
How can I create key-value attributes?
Try this code
function get_attribute_id_from_name($name)
{
global $wpdb;
$attribute_id = $wpdb->get_var("SELECT attribute_id
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
WHERE attribute_name LIKE '$name'");
return $attribute_id;
}
function save_product_attribute_from_name($name, $label = '', $set = true)
{
if (!function_exists('get_attribute_id_from_name')){
return;
}
global $wpdb;
$label = $label == '' ? ucfirst($name) : $label;
$attribute_id = get_attribute_id_from_name($name);
$taxonomy = wc_attribute_taxonomy_name($name); // The taxonomy slug
if (empty($attribute_id)) {
$attribute_id = NULL;
}
else {
$set = false;
}
//register existing taxonomy
if (isset($attribute_id) && !taxonomy_exists($taxonomy)) {
register_attribute($name);
}
$args = array(
'attribute_id' => $attribute_id,
'attribute_name' => $name,
'attribute_label' => $label,
'attribute_type' => 'select',
'attribute_orderby' => 'menu_order',
'attribute_public' => 0,
);
if (empty($attribute_id)) {
$wpdb->insert("{$wpdb->prefix}woocommerce_attribute_taxonomies", $args);
set_transient('wc_attribute_taxonomies', false);
}
if ($set) {
$attributes = wc_get_attribute_taxonomies();
$args['attribute_id'] = get_attribute_id_from_name($name);
$attributes[] = (object)$args;
//print_r($attributes);
set_transient('wc_attribute_taxonomies', $attributes);
} else {
return;
}
}
function register_attribute($name)
{
$taxonomy = wc_attribute_taxonomy_name($name); // The taxonomy slug
$attr_label = ucfirst($name); // attribute label name
$attr_name = (wc_sanitize_taxonomy_name($name)); // attribute slug
register_taxonomy(
$taxonomy,
'product',
array(
'label' => __($attr_label),
'rewrite' => array('slug' => $attr_name),
'hierarchical' => true,
)
);
}
function add_product_attribute($product_id, $data)
{
$_pf = new WC_Product_Factory();
$product = $_pf->get_product($product_id);
$product_attributes = array();
foreach ($data['_attributes'] as $key => $terms) {
$taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
$attr_label = ucfirst($key); // attribute label name
$attr_name = (wc_sanitize_taxonomy_name($key)); // attribute slug
// NEW Attributes: Register and save them
if (!taxonomy_exists($taxonomy))
save_product_attribute_from_name($attr_name, $attr_label);
$product_attributes[$taxonomy] = array(
'name' => $taxonomy,
'value' => '',
'position' => '',
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 1
);
foreach ($terms as $value) {
$term_name = ucfirst($value);
$term_slug = sanitize_title($value);
// Check if the Term name exist and if not we create it.
if (!term_exists($value, $taxonomy))
wp_insert_term($term_name, $taxonomy, array('slug' => $term_slug)); // Create the term
// Set attribute values
wp_set_object_terms($product_id, $term_name, $taxonomy, true);
}
$product->set_attributes(array($attribute));
}
update_post_meta($product_id, '_product_attributes', $product_attributes);
}
Then call function
add_product_attribute(76, [
'attributes' => [
'Attribute 1' => ['Value 1', 'Value 2'],
'Attribute 2' => ['Value 4', 'Value 5'],
],
]
);
I created a custom endpoint for specific data from a custom table in my Wordpress plugin. It get's all the data from the table with the getHelpers() function. After that it will be merged by some user data. I would like to add the profile_image as a link to the response so we can get it with the embed parameter.
What is the best way to add the link to the response? I know the $response->add_link() function but this would add it to the response and not to each contributor.
I tried to add the link as an array but this won't react on the _embed parameter.
This is my code for the custom endpoint:
class VEMS_Rest_Contributors extends WP_REST_Controller {
protected $namespace = 'vems/v2';
protected $rest_base = 'contributors';
/**
* Register the routes for coupons.
*/
public function register_routes() {
register_rest_route( $this->namespace, '/' . $this->rest_base, array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'args' => $this->get_collection_params(),
) );
}
public function get_items( WP_REST_Request $request ) {
$project_id = $request->get_param( 'project_id' );
$contributors = array();
if( !empty($project_id) ) {
$project = new VEMS_Project( $request['project_id'] );
$helpers = $project->getHelpers();
foreach($helpers as $helper) {
$contributor = array();
if( !empty($helper->contributor_id) ) {
$user = get_user_by( 'ID', $helper->contributor_id );
$user_meta = get_user_meta( $helper->contributor_id );
$contributor['ID'] = $helper->contributor_id;
$contributor['user_nicename'] = $user->data->display_name;
$contributor['user_profile_image'] = $user_meta['contributor_profile_image'][0];
} else {
$contributor['user_nicename'] = $helper->name;
$contributor['user_profile_image'] = $helper->image_id;
}
$contributor['item_total'] = $helper->item_total;
$contributor['checked'] = $helper->checked;
$contributor['helper_date'] = $helper->helper_date;
/*
$contributor['_links']['profile_image'] = array(
'href' => rest_url( '/wp/v2/media/' . $contributor['user_profile_image'] ),
'embeddable' => true
);
*/
$contributors[] = $contributor;
}
}
$response = rest_ensure_response( $contributors );
return $response;
}
public function get_collection_params() {
$params['project_id'] = array(
'description' => __( 'Limit result set to contributors assigned a specific project.', 'vems' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
);
return $params;
}
}
to handle links on route vems/v2/contributors?_embed, the element profile_image must be an array of links and then you can do that
$contributor['_links']['profile_image'] = [
[
'href' => rest_url( '/wp/v2/media/' . $contributor['ID'] ),
'embeddable' => true,
],
];
I'm trying to create a new post (type event) every time one of my posts is updated and custom_field has the value 'ja'.
I don't understand why the if query if($customfield == 'ja'){}
doesn't work.
function create_event($post_id, $post, $post_before){
if (get_post_type($post) == 'product') {
$customfield=get_post_meta($post_id, 'custom_field');
if ($customfield == 'ja') { //this if query doesn't work
$author = $post->post_author;
$event = array(
'post_type' => 'tribe_events',
'post_title' => get_the_author_meta('firmenname', $author),
'meta_input' => array('post_id' => $post_id, '_EventStartDate' => '2019-06-04 00:00', '_EventEndDate' => '2019-06-04 23:59',
'test'=>$customfield)
);
wp_insert_post($event);
}
}
add action('post_updated', 'create_event', 10, 3);
function create_event($post_id, $post, $post_before){
if (get_post_type($post) == 'product') {
$customfield=get_post_meta($post_id, 'custom_field', true);
if ($customfield == 'ja') { //this if query doesn't work
$author = $post->post_author;
$event = array(
'post_type' => 'tribe_events',
'post_title' => get_the_author_meta('firmenname', $author),
'meta_input' => array('post_id' => $post_id, '_EventStartDate' => '2019-06-04 00:00', '_EventEndDate' => '2019-06-04 23:59',
'test'=>$customfield)
);
wp_insert_post($event);
}
}
add action('post_updated', 'create_event', 10, 3);
to get value in variable you need to write this
$customfield=get_post_meta($post_id, 'custom_field', true);
I am trying to modify a plugin. I need the author id of the current post to accomplish what I am doing. I have tried every other method I have found over internet that claims to get the post author id outside the loop but its not working inside the plugin. I guess its because the plugins might be loaded before the loop variables or something? Please pardon me as I am not a Pro.
Here is what I have tried so far.
1.
$author_id=$post->post_author;
2.
global $post;
$author_id=$post->post_author;
3.
$post_tmp = get_post($post_id);
$author_id = $post_tmp->post_author;
4.
$author_id = $posts[0]->post_author;
But nothing works in the plugin's directory. Can anyone help?
Detailed Explanation:
I am trying to modify woodiscuz plugin. The problem with this plugin is that it held comments of even seller for moderation. So if I am the seller and I reply to some buyer in comment, I will have to approve my own comment.
Now to overcome this problem, I am putting a condition that if the author of the post (seller) is commenting, then don't put the comment for moderation.
Here is the function of the plugin that is controlling comments.
public function comment_submit_via_ajax() {
$message_array = array();
$comment_post_ID = intval(filter_input(INPUT_POST, 'comment_post_ID'));
$comment_parent = intval(filter_input(INPUT_POST, 'comment_parent'));
if (!$this->wpc_options->wpc_options_serialized->wpc_captcha_show_hide) {
if (!is_user_logged_in()) {
$sess_captcha = $_SESSION['wpc_captcha'][$comment_post_ID . '-' . $comment_parent];
$captcha = filter_input(INPUT_POST, 'captcha');
if (md5(strtolower($captcha)) !== $sess_captcha) {
$message_array['code'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_captcha'];
echo json_encode($message_array);
exit;
}
}
}
$comment = filter_input(INPUT_POST, 'comment');
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$user = get_userdata($user_id);
$name = $user->display_name;
$email = $user->user_email;
$user_url = $user->user_url;
} else {
$name = filter_input(INPUT_POST, 'name');
$email = filter_input(INPUT_POST, 'email');
$user_id = 0;
$user_url = '';
}
$comment = wp_kses($comment, array(
'br' => array(),
'a' => array('href' => array(), 'title' => array()),
'i' => array(),
'b' => array(),
'u' => array(),
'strong' => array(),
'p' => array(),
'img' => array('src' => array(), 'width' => array(), 'height' => array(), 'alt' => array())
));
$comment = $this->wpc_helper->make_clickable($comment);
if ($name && filter_var($email, FILTER_VALIDATE_EMAIL) && $comment && filter_var($comment_post_ID)) {
$held_moderate = 1;
if ($this->wpc_options->wpc_options_serialized->wpc_held_comment_to_moderate) {
$held_moderate = 0;
}
// $held_moderate = 1 -> No moderation
/*This is the part where I need to put the custom condition*/
if($post_author_id == get_current_user_id())
{
$held_moderate = 1;
}
$new_commentdata = array(
'user_id' => $user_id,
'comment_post_ID' => $comment_post_ID,
'comment_parent' => $comment_parent,
'comment_author' => $name,
'comment_author_email' => $email,
'comment_content' => $comment,
'comment_author_url' => $user_url,
'comment_type' => 'woodiscuz',
'comment_approved' => $held_moderate
);
$new_comment_id = wp_insert_comment($new_commentdata);
$new_comment = new WPC_Comment(get_comment($new_comment_id, OBJECT));
if (!$held_moderate) {
$message_array['code'] = -2;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_held_for_moderate'];
} else {
$message_array['code'] = 1;
$message_array['message'] = $this->comment_tpl_builder->get_comment_template($new_comment);
}
$message_array['wpc_new_comment_id'] = $new_comment_id;
} else {
$message_array['code'] = -1;
$message_array['wpc_new_comment_id'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_field'];
}
echo json_encode($message_array);
exit;
}
I'm using a form on add and edit page in which there is a input file which is required for add record but it is not required on edit page. Is there a way to change attribute on different pages?
$builder->add('title', 'text', array(
'required' => true,
))->add('description', 'textarea', array(
'required' => false,
))->add('fileName', 'file', array(
'data_class' => null,
'required' => true,
'label' => 'Upload File'
));
this is my controller
if ($custFile === null) {
$custFile = new File();
}
$fileForm = $this->createForm(new CustomerFileType(), $custFile);
$fileForm->handleRequest($request);
if ($fileForm->isValid()) {
$data = $fileForm->getData();
$custFile->setUserType('customer');
$custFile->setUserId($request->get('id'));
$custFile->setDateAttached($data->date);
$om->persist($data);
$file = $custFile->getFileName();
if ($file instanceof UploadedFile) {
$uploadManager = $this->get('probus_upload.upload_manager.user_files');
if ($newFileName = $uploadManager->move($file)) {
$custFile->setFileName(basename($newFileName));
}
}
$om->flush();
return $this->redirect($this->generateUrl('minicasp_customer_edit_customer', array(
'id' => $request->get('id'),
)));
}
$fileRecord = array();
if (null !== $customer) {
$fileRecord = $om->createQueryBuilder()
->from('MinicaspCustomerBundle:file', 'f')
->select('f')
->where('f.userId = :customer')
->andWhere('f.userType = :userType')
->orderBy('f.id', 'DESC')
->setParameter('customer', $request->get('id'))
->setParameter('userType', 'customer')
->getQuery()
->getResult()
;
}
return $this->render('MinicaspCustomerBundle:Default:customerAccount.html.twig', array(
'form' => $form->createView(),
'payment_form' => $paymentForm->createView(),
'file_form' => $fileForm->createView(),
'payments' => $payments,
'file_record' => $fileRecord,
'file_edit' => $fileEdit
));
Get your object inside form class and check if your add or edit new record, and based by this set the value of "required" attribute:
$obj = $builder->getData();
$builder->add('fileName', 'file', array(
'data_class' => null,
'required' => $obj->getId() === null ? true : false,
'label' => 'Upload File'
));
#Umair Malik, according to your last comment, you can try this in your controller:
if ($request->getMethod() == 'POST') {
$form->submit($request);
$formData = $form->getData();
if ($formData->getFile() !== null){
/*
* New file has been uploaded
* Save or copy your old record; after this will be over-written
*/
}
$entityManager->persist($formData);
$entityManager->flush();
}
You can create two form types, with different options.
On a side note, you don't need to put "required => true" that's the default option,