How to edit layout of orders table (orders.php) - php

I want to change the layout of table present in orders.php. Specifically, instead of having rows containing the data (name, date, status, etc.), I want separate horizontal cards for each product.
Example: https://i.stack.imgur.com/itdGU.png. I'm trying to do this with a shortcode, but I'm not sure if that's the right way. Can anyone give me directions ?
For now I'm trying this way: The code below works and returns all order numbers correctly. However I am getting all the order numbers side by side as a simple line of text: https://i.stack.imgur.com/RqdVC.png. I don't know how to insert div, or css classes to change the layout.
Even if I add css classes, the question that remains is how to add other elements such as name, price, status etc. Not sure it can all be done in one shortcode. Advice ?
// GET ALL ORDERS NUMBER OF CURRENT USER
// Give the callback function a clear and descriptive name.
add_shortcode( 'prcsed_order_numbers' , 'prcsed_order_1' );
function prcsed_order_1() {
// Get all orders for the current user.
$customer_orders = wc_get_orders([
'customer_id' => get_current_user_id(),
]);
// Transform the array of order objects into an array of order names.
$order_numbers = array_map( function( $order ) {
return $order->get_order_number();
}, $customer_orders );
// Return as a string, ready for output,
return implode( ', ', $order_numbers );
}

Expanding on what I was typing before. You can access more order variables using what you were already doing in $order_numbers. Here is what I have tested on standalone WooCommerce test site. You will need to input your customer ID function and modify the return HTML structure for styling and editing simplicity. What I have is not clean but does work.
$results = wc_get_orders([ 'cutomer_id'=>1 ]);
foreach ( $results as $order ) {
$first_name = $order->get_billing_first_name();
$last_name = $order->get_billing_last_name();
$status = $order->get_status();
echo '<h1>' . $first_name . ' ' . $last_name . '</h1><p>' . $status . '</p>';
}
The following link gives you the functions/hooks for the order object that you will need accessing to. https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/

Related

AffiliateWP + WooCommerce - Need Method of Pulling Nickname from ID

So, this one has my head in for a loop. I've contacted the Support of the plugin and they basically told me I'm SOL, but I refuse to believe there isn't a way to do this.
I'm using AffiliateWP to attribute sales to a single location. Each Affiliate feeds off of a Wordpress User, and for their nickname I've used their address/location.
Unfortunately, the plugin doesn't include this in the Order Details screen or Order Emails, which is a BIG problem. I've frankensteined some code together but keep getting all kinds of undefined errors because they do everything inside classes, which I guess makes sure that people like me can't fiddle in there?
Function for assigning an affiliate to an order: https://github.com/AffiliateWP/AffiliateWP/blob/master/includes/integrations/class-woocommerce.php#L78
Function for retrieving the Affiliates User ID: https://github.com/AffiliateWP/AffiliateWP/blob/master/includes/affiliate-functions.php#L204
Function for retrieving the Affiliates Name: https://github.com/AffiliateWP/AffiliateWP/blob/master/includes/affiliate-functions.php#L132
[Edit] And finally, my Frankenstein:
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
global $Affiliate_WP_WooCommerce;
echo '<p><strong>'.__('My Field').':</strong> ' . affiliate_wp()->affiliates->get_affiliate_name( $affiliate_id ) . '</p>';
}
This doesn't throw me an error, but it does throw me a blank area...
Try this:
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
global $Affiliate_WP_WooCommerce;
$order_id = $order->get_id();
$referrals = affiliate_wp()->referrals->get_by( 'reference', $order_id);
$affiliate_id = $referrals->affiliate_id;
echo '<p><strong>'.__('My Field').':</strong> ' . affiliate_wp()->affiliates->get_affiliate_name( $affiliate_id ) . '</p>';
}
the affwp_get_affiliate_name method returns blank on three conditions:
if ( ! $affiliate = affwp_get_affiliate( $affiliate ) ) {
return '';
}
if ( ! $user_info = get_userdata( $affiliate->user_id ) ) {
return '';
}
...
// If neither are set, return an empty string.
if ( empty( $first_name ) && empty( $last_name ) ) {
return '';
}
Start by manually passing an affiliate id you know to be associated with a record that contains a $first_name and/or $last_name, for example:
echo '<p><strong>'.__('My Field').':</strong> ' . affiliate_wp()->affiliates->get_affiliate_name(5) . '</p>';
This will rule out if the problem is with the $affiliate_id that you're currently passing it. If you get values returned, it should be a simple matter to fix.
After trying that I would experiment with changing the priority of the add_action(), raising it to 999 or something because it could possibly be executing before the relevant hooks in the plugin.

Searching a custom table in wordpress

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();

Displaying and getting only the child categories

I have a section on my wordpress website that currently displays the child and parent categories of a listing. I would like for only the child categories to be displayed. I wasn't able to figure out the solution on my own, your help is appreciated.
Here is the current code I'm using for this (which also displays parent categories):
<?php
//NEW
$permalink = get_permalink( $id );
//NEW
$seo = get_the_title()." : ";
$Category_links = ' Found in the ';
$term_list_category = wp_get_post_terms(get_the_ID(), 'listings_categories', array("fields" => "ids"));
//THIS CODE REMOVES PARENTS FROM BEING DISPLAYED IN THE LISTING CATEGORIES
foreach ($term_list_category as $k=>$term) {
$children = get_term_children( $term, 'listings_categories');
if ($children)
unset($term_list_category[$k]);
}
$i = 0;
$count = count($term_list_category);
if ( $count > 0 ){
foreach ( $term_list_category as $term_category ) {
$thisCat = get_term_by( 'id', $term_category, 'listings_categories');
//NEW
$url = '<a id="'.$term_category.'" slug="'.$thisCat->{'slug'}.'" class="listing-links-cat" href="#" title="'.$thisCat->{'name'}.'" >'.$thisCat->{'name'}.'</a>';
$i ++;
$seo .= " " . $thisCat->{'name'} . "";
$Category_links .= " " . $url . "";
if($count-1 == $i){
$Category_links .= " and "; $seo .= ", ";
}elseif($count > 1 && $count !== $i){
$Category_links .= ", "; $seo .= ", ";
}
}
$Category_links .= " Categories";
?>
<? echo $Category_links; ?>
But I feel that the overall code can be improved for performance, so it doesn't search the database as much?
Your code is quite ineffecient and also have unnecessary parts to it. Your additional part makes your code even more ineffecient and causes you to hit the db hard.
FLAWS
You get plus 1 for only getting the term id's from the post terms, but unfortunately in this specific case, this tampers your code and this is the starting point of your ineffeciency as you then need to use get_term_by() on every iteration of your foreach loop. This means extra db calls on every iteration for something that should have already been there
The use of get_term_children() adds to the amount of db calls made on every iteration of your foreach loop. Again, you are making unnecessary db calls for something that should have been there in the first place
It is totally unnecessary to count the amount of terms returned by wp_get_post_terms. This adds extra ineffeciency to your code. wp_get_post_terms returns an empty array if no terms exists or a WP_Error object if the taxonomy does not exist. Keep this in mind for later on
SPEEDING IT UP AND STREAMLINING THE CODE
Lets look at what we can do to make your code more effecient
Remove the fields parameter from wp_get_post_terms. As we need more than just the ids of the terms, we need to return the complete term object. You might think that this is ineffecient, but this will save you a lot of db hits and most importantly, time, as you are getting rid of get_term_by() and get_term_children()
There is no proper way to remove parents from wp_get_post_terms(), so the best way will be to just loop over them and ignore/skip them with continue. I assume you are talking about top level terms which have 0 assigned to its $parent property, so you just need to check that the parent value is not 0
Always do proper failure checks. If you don't do that, and your code fails, php error and notices are returned, which is known as bugs. You would want to avoid that. Also, you would always want your code to fail in a controlled, expected manner without bugs. As I stated before, wp_get_post_terms() returns an empty array or a WP_Error object, so this is what you need to check for. If any of these cases occur, immediately halt execution and return the function to avoid bugs and unexpected output
PUTTING THE ABOVE IN CODE
I like to keep my template files short and sweet. For that reason, bulky code the above always goes into a function and I then just call the function in my template files where necessary. Also, just a tip, I have function specific functions files to keep my code organised and not to overload functions.php. my functions.php file is usually not more than 100 lines of code.
For example, this is part of your post's meta, so this will go into a file with other meta functions like displaying the autor name and post date.
function get_post_child_terms( $taxonomy = '' )
{
$current_post = get_queried_object_id();
$terms = wp_get_post_terms( $current_post, $taxonomy );
/*
* Check if $taxonomy has a value, also check for WP_Error or empty $terms. If any of these conditions
* are met, halt execution and return false
*/
if ( !$taxonomy || is_wp_error( $terms ) || empty( $terms ) )
return false;
/*
* We have made it to here safely, now iterate over the terms
*/
foreach ( $terms as $term ) {
/*
* Check for parent terms and ignore them
*/
if ( $term->parent == 0 )
continue;
/*
* Get an array of term names
*/
$term_names[] = $term->name;
}
/*
* Build our string of names
*/
if ( !isset( $term_names ) )
return false;
$string = 'Some text here maybe to start of: ' . implode( ',', $term_names ) . 'Maybe something at the end';
return $string;
}
USAGE
You can now simply call the function in your template as follow:
echo get_post_child_terms( 'listings_category' );
This will produce a list like this
Some text here maybe to start of: Term name 1, Term name 2, Term name 3 Maybe something at the end
FINAL NOTES
The code above is untested and might be a bit buggy.
The code above is the very least that you need. You can extend and misuse it as you see fit to fit your exact needs. A few ideas for extension might be to work in some arguments to where you can choose to display the parent terms or not, and whether the function should return a string of term names or an array of term names. The sky is the limit here
You can build in a cache system to cache your results to optimize these even further.
EDIT
The above code is now tested and is working as expected

How to skip certain links on adjacent posts in Wordpress?

I use the following code to fetch the links of the previous and next posts respectively, from the single post template;
<?php echo get_permalink(get_adjacent_post(false,'',false)); ?>
<?php echo get_permalink(get_adjacent_post(false,'',true)); ?>
My question is, please, if there are certain posts I'd like these codes to skip, and simply go to the ones right after, could I do that somehow using custom fields, or otherwise how can I make Wordpress skip a certain link when it comes up and fetch the next adjacent one without first going to the one I'd like to skip and then redirect or something, but rather echo the correct one right away..?
Thank you very much!
Alex
You can approach this in different ways. The easiest solution would probably be to use an "excluded category" (second parameter), e.g. exclude posts from category with term ID 5:
get_adjacent_post( false, '5', false )
Another option is to use the get_previous_post_where and get_next_post_where filters to modify the SQL query.
You could store in the options table an array of post IDs to be excluded, here's an example how you could exclude all sticky posts:
add_filter( 'get_previous_post_where', 'so16495117_mod_adjacent' );
add_filter( 'get_next_post_where', 'so16495117_mod_adjacent' );
function so16495117_mod_adjacent( $where ) {
return $where . ' AND p.ID NOT IN (' . implode( ',', get_option( 'sticky_posts' ) ) . ' )';
}
Or, as you suggested in your Q, you could filter out posts that have a certain post meta key, e.g. my_field:
add_filter( 'get_previous_post_where', 'so16495117_mod_adjacent_bis' );
add_filter( 'get_next_post_where', 'so16495117_mod_adjacent_bis' );
function so16495117_mod_adjacent_bis( $where ) {
global $wpdb;
return $where . " AND p.ID NOT IN ( SELECT post_id FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = p.ID ) AND $wpdb->postmeta.meta_key = 'my_field' )";
}

Ordering Wordpress posts based on parent category

UPDATE: I have tried using the following code:
<?php if (is_category(events)) {
$posts = query_posts($query_string . '&orderby=event_date&order=desc');
} else {
$posts = query_posts($query_string . '&orderby=title&order=asc');
}
?>
Is there any reason why that wouldnt work? It seems to work fine organising posts in alphabetical order, but still no luck on the date order within 'events'.
--
After searching through various existing questions I can't quite find a solution to what I am trying to do.
Currently all posts on my site are ordered alphabetically, which is fine except for one new category that I have added. For this category I want to order all posts by a value that I enter into a custom field. The field is called 'event_date' - so I want to order the posts by date essentially, but not the date the post was created, the date the user manually enters into this field.
I managed to get it working by using:
<?php if (is_category($events)) { $posts = query_posts($query_string . '&orderby=$event_date&order=asc'); } ?>
However this overrides the aphabetical order for all other pages.
For alphabetical order I am using:
<?php if (is_category()) { $posts = query_posts( $query_string . '&orderby=title&order=asc' ); } ?>
Essentially I want a statement that tells the page to order all posts in aphabetical order, unless the category is 'events', where I want to order them by the custom event date.
As you can probably tell I'm very much front end, not back end so a lot of this is fairly new to me, so any help or advice is appreciated.
To order posts by a custom field value, you need add the custom meta field to the query itself. orderby=meta_value in addition to meta_key=metafieldid will allow ordering in this fashion.
I would use the pre_get_posts hook and modify the query object if get_query_var( "cat" ) (or a similar query var) returns the desired post category.
add_action( "pre_get_posts", "custom_event_post_order" );
function custom_event_post_order( $query )
{
$queried_category = $query -> get_query_var( "cat" );
/*
* If the query in question is the template's main query and
* the category ID matches. You can remove the "is_main_query()"
* check if you need to have every single query overridden on
* a page (e.g. secondary queries, internal queries, etc.).
*/
if ( $query -> is_main_query() && $queried_category == 123 )
{
$query -> set( "meta_key", "event_date" ); // Your custom field ID.
$query -> set( "orderby", "meta_value" ); // Or "meta_value_num".
$query -> set( "order", "ASC" ); // Or "DESC".
}
}
Remember that this approach overrides all queries that are using the category in question. You can build custom WP_Query objects that use their own parameters for constructing loops.
You also should standardize the way you save the custom field data to the database. For dates I prefer using UNIX-timestamp formatted times that are easy to move around and manipulate. This way no accidents happen when querying and some data is formatted in another way that the rest is.
Disclaimer: I did not have the time to test the above code in action, but the general idea should work properly.
EDIT: of course the above code should be inserted to functions.php or a similar generic functions file.
What about:
<?php $posts = query_posts($query_string . (is_category($events)?'&orderby='.$event_date:'&orderby=title') . '&order=asc'); ?>
<?php
$recent = new WP_Query(“cat=ID&showposts=x”);
while($recent->have_posts()) : $recent->the_post();
?>
Hopefully I understood your question, use the WP_Query and within the orderby add a space between your order by columns:
$args = array(
'posts_per_page' => 100,
'orderby' => 'title',
'order' => 'ASC',
);
if(is_category($events)){
$args['orderby'] .= " meta_value_num";
$args['meta_key'] = 'event_date';
}
$posts = (array) new WP_Query( $args );

Categories