Show message if no orders in woocommerce - function

I would like to display a message in my-account if the customer has no orders I would like to show "No orders currently".
I guessing there's a function I could use to hook into this somewhere?
Had a good search and cant find anything to get me started.
Thanks.

Modifying from this tutorial I think this would work:
function wc_get_customer_orders() {
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => 1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => wc_get_order_types(),
'post_status' => array_keys( wc_get_order_statuses() ),
) );
$customer = wp_get_current_user();
// Text for our message
$notice_text = sprintf( 'Hey %1$s 😀 We noticed you haven\'t placed any orders with us.', $customer->display_name );
// Display our notice if the customer has no orders
if ( count( $customer_orders ) == 0 ) {
wc_print_notice( $notice_text, 'notice' );
}
}
add_action( 'woocommerce_before_my_account', 'wc_get_customer_orders' );
Basically, on the account page we query for a single order by the currently logged in user. If we don't get an order back we show the notice.

Copied my-orders.php to local folder and added an else clause:
else{
echo "No orders";
}
This can be styled using WC css

Related

If the product does not have the "_price" meta key, remove the product

I have created code as below and the focus part is PM.meta_key !='_price' and I don't know how true it is, it didn't work but it's also possible to remove all products otherwise, I need a correct way.
Also here is a picture, some products don't have the "_price" key and this way the product looks very bad, the strange thing is that they are still in stock.
Here is an example photo.
add_action( 'init', 'automatically_trash_instock_empty_price' );
function automatically_trash_instock_empty_price() {
// Get any existing copy of our transient data
if ( false === ( $automatically_trash_instock_empty_price = get_transient( 'automatically_trash_instock_empty_price' ) ) ) {
// It wasn't there, so regenerate the data and save the transient
global $wpdb;
$wpdb->query( "UPDATE {$wpdb->posts} P JOIN {$wpdb->postmeta} PM ON P.ID = PM.post_id SET P.post_status='trash' WHERE P.post_type='product' and PM.meta_key != '_price'" );
set_transient( 'automatically_trash_instock_empty_price', true, 1 * HOUR_IN_SECONDS );
}
}
I know you asked for MySQL query but why not use native functions for this? You can query all your products and foreach create a product object using the following function:
$product = wc_get_product( $post_id );
And after that you will be able to access all product's data. All available methods can be found here, but the ones you probably need are:
$product->get_regular_price();
$product->get_sale_price();
$product->get_price();
Then check if $product->get_price(); is null, empty and/or zero and just:
wp_trash_post($product->get_id());
Trash post doc
Finally, you could also set this up as a cron job to run daily/weekly and clean up your products regularly.
EDIT
As per your comments here is a full working example of a scheduled function via wp-cron to do what you asked regularly:
// Your scheduled function
function trash_products_without_price_stock() {
$get_all = new WP_Query(
array(
'post_type' => 'product',
'posts_per_page' => -1,
)
);
if ( $get_all->have_posts() ) :
while ( $get_all->have_posts() ) :
$get_all->the_post();
// Start : Your conditionals here
if ( ! get_post_meta( get_the_ID(), '_price', true ) && get_post_meta( get_the_ID(), '_stock', true ) ) {
wp_trash_post( get_the_ID() );
}
// End
endwhile;
wp_reset_postdata();
endif;
}
// Schedule Cron Job Event
if ( ! wp_next_scheduled( 'clean_my_products' ) ) {
// here you can use 'hourly', 'twicedaily', 'daily', and 'weekly'
wp_schedule_event( time(), 'daily', 'clean_my_products' );
}
add_action( 'clean_my_products', 'trash_products_without_price_stock' );
Put the above in functions.php

Populate WordPress Advanced Custom Fields with remote JSON in backend

I have custom post types called "Products". and using the AFC(Advanced Custom Fields) plugin with this post type.
Below is what ACF has in fields group
- one filed called 'Product Description' as text area
- three text fields called 'Feature 1, Feature 2,Feature 3'
What I want to achieve is to get the data from external JSON file and populate the above ACF fields in the backend. I did some research and found Wordpress offers wp_remote_get() function to request the remote file. But I have no clue where to begin with to use this function or any other approach to use external JSON and populate these fields. Will really appreciate it someone points me to the right direction or any tutorial that shows how to achieve that. Thanks
I figured it out. View the working code below.
// Get JSON and Decode
$json_request = wp_remote_get( 'http://wp-test/test/data.json');
if( is_wp_error( $json_request ) ) {
return false;
}
$json_body = wp_remote_retrieve_body( $json_request );
$json_data = json_decode( $json_body );
// Create the new post and populate the fields
foreach( $json_data->products as $item ) {
$title = $item->title;
$desc = $item->content;
$status = $item->status;
$new_post = array(
'post_title' => $title,
'post_content' => $desc,
'post_status' => $status,
'post_author' => $userID,
'post_type' => 'products'
);
$post_id = post_exists( $title );
if (!$post_id) {
$post_id = wp_insert_post($new_post);
}
}

ACF front end form to update term

I want to use ACF frontend form function to create a form with custom fields
I see this issue for create new term, #Alhana
ACF front end form to create term
but I want to generate the form with old data
Well, i didn't see that question, but if it's still actual, here's a solution.
First of all, make sure you have ACF group, linked to your taxonomy. You will need ID of this group, it can be found in url on group edit page, for example:
http://site.ru/wp-admin/post.php?post=340&action=edit
In this case group ID is 340. If you don't want to use hardcoded ID (if your groups are changing from time to time), you can get it, using group name (in this example group name is Technic CPT):
global $wpdb;
$group_ID = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = 'Technic CPT'" );
Then, you'll need ID of term you're updating. I think, it's not nesessary to write about getting it since it's WP basics :) You'll end with something like this:
$term_id = 405;
And finally, you'll need your taxonomy's slug. In this example it's technic. So, let's render our form!
acf_form_head();
$acf_form_args = array(
'id' => 'technic_edit_form',
'post_id' => 'technic_'.$term_id,
'form' => true,
'submit_value' => 'Update technic',
'field_groups' => array($group_ID),
'updated_message' => 'Technic is updated!';
);
acf_form( $acf_form_args );
Now your term's custom fields will be shown in this form. But to save term data after editing you'll need to add some more code. ACF form assumes that you're saving post data, we'll add some logic to detect saving data for term.
add_filter( 'acf/pre_save_post', 'acf_handle_form_save', 10, 1 );
function acf_handle_form_save( $post_id ) {
// Function accepts id of object we're saving.
// All WordPress IDs are unique so we can use this to check which object it is now.
// We'll try to get term by id.
// We'll get term id with added taxonomy slug, for example 'technic_405'.
// For checking term existence we must cut out this slug.
$cut_post_id = str_replace( 'technic_', '', $post_id );
$test_tax_term = get_term_by( 'id', $cut_post_id, 'technic' );
// If $test_tax_term is true - we are saving taxonomy term.
// So let's change form behaviour to saving term instead of post.
if ( $test_tax_term ) :
// Get array of fields, attached to our taxonomy
global $wpdb;
$group_ID = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = 'Technic CPT'" );
$acf_fields = acf_get_fields_by_id( $group_ID );
// Then sanitize fields from $_POST
// All acf fields will be in $_POST['acf']
foreach ( $acf_fields as $acf_field ) :
$$acf_field[ 'name' ] = trim( esc_attr( strip_tags( $_POST[ 'acf' ][ $acf_field[ 'key' ] ] ) ) );
endforeach;
// We need to have some fields in our group, which are just duplicates of standard term fields: name, slug, description.
// In this example it's only one field - term name, called 'technic_name'.
$name = 'technic_name';
// Update base term info, in this example - only name.
$term = wp_update_term( $cut_post_id, 'technic', array( 'name' => $$name ) );
// If all is correct, update custom fields:
if ( !is_wp_error( $term ) ) :
foreach ( $acf_fields as $acf_field ) :
update_field( $acf_field[ 'name' ], $$acf_field[ 'name' ], 'technic_' . $cut_post_id );
endforeach;
endif;
else :
// Here is saving usual post data. Do what you need for saving it or just skip this point
endif;
return $post_id;
}
Please note: validation of $_POST data may be more complex. For example, you may have to validate array of values if there are ACF galleries or relationships among your taxonomy fields. In my example i have only common text fields.
Hope that helps!
The answer from Alhana worked for me with one change. The term object works if sent as the the value for the post_id:
$term_obj = get_term($term_id);
$acf_form_args = array(
'post_id' => $term_obj,
'post_title' => false,
'submit_value' => 'Update Term',
'field_groups' => array($group_ID),
);

Table which can add, edit ,and delete data dynamically in Drupal

I know that we can add edit and delete data in a table statically in Drupal. But is there any way we can add edit and delete data via clicking a link just near to each row so that on clicking "add " button should generate a new row, and on clicking edit should highlight all the contents of the row as fr editing and delete should remove the row. The basic table I created is this:
<?php
$header = array('Emp ID', 'Emp Name', 'Emp Age');
$rows = array();
$sql = 'SELECT empid, name, age FROM {employee} ORDER BY name';
$result = db_query($sql);
while ($row = db_fetch_array($result)) {
$rows[] = $row;
}
print theme('table', $header, $rows);
?>
You can build it. You've already got your Read mode, so you need a Create/Update/Delete... there is some help on the internet for basic CRUD modules. Very basically, the update part, (first having a menu hook using % wildcard which is what arg(1) will be:
function crud_module_edit_form() {
$result = db_select('employee', 'e')
->fields('e', array('empid', 'name'))
->condition('empid', arg(1), '=')
->orderBy('name', 'DESC')
->execute()
->fetch();
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#default_value' => isset($result->name) ? $result->name : '',
'#required' => TRUE,
);
return $form;
}
Then the submit function for the above form to update the record. You could use db_merge here instead and then use the same page for both the Add and the Update functions.
function crud_app_edit_form_submit($form, &$form_state) {
db_update('employees')
->fields(array(
'name' => check_plain($form_state['values']['name']),
))
->condition('empid', arg(1), '=')
->execute();
drupal_set_message(t('Employee updated'));
}

query post to different role users in wordpress

Is it possible to show different posts to a different role users?? I need something like this
User A => Post A ||
User B => Post B
I can't use UserID, because there will be a lot of users. I was thinking something like this
<?php
if ( is_userA_logged_in() ) {
echo 'Welcome A user!'; //here comes the query
} elseif ( is_userB_logged_in() ) {
echo 'Welcome B user!'; // here comes the query
}
?>
I was reading on the codex but I only found the is_admin(), how can I call a new role?
I'd create the new roles in the functions.php with
<?php
add_role('userA', 'User A', array(
'read' => true, // True allows that capability
'edit_posts' => false,
'delete_posts' => false, // Use false to explicitly deny
));?>
See the current_user_can function.
if ( current_user_can( $role ) )
$q = get_query();
Also, check functions like get_currentuserinfo and get_userdata.