Variable width on posts using post count - wordpress

I'm setting up a loop and with help from the $count I want to have different classes to the posts.
However, I want the $count to be dynamic, now I have to manually state the class depending on if the post count is equal to a number or not, as you can see in the code below.
$args = array(
'post_type' => 'post',
'posts_per_page' => -1
);
$loop = new WP_query( $args );
$count = 0;
while ( $loop->have_posts() ) : $loop->the_post();
$count++;
if( $count == 1) {
get_template_part( 'parts/case/item','six');
} elseif ( $count == 2) {
get_template_part( 'parts/case/item','three');
} elseif ( $count == 3) {
get_template_part( 'parts/case/item','three');
} elseif ( $count == 4) {
get_template_part( 'parts/case/item', 'six');
} elseif ( $count == 5) {
get_template_part( 'parts/case/item', 'six');
} elseif ( $count == 6) {
get_template_part( 'parts/case/item', 'three');
} else {
get_template_part( 'parts/case/item', 'three');
}
?>
<?php endwhile; wp_reset_postdata();?>
The number six and three are the classes of the posts.
What I want to execute.
Post 1 = class 6
Post 2 = class 3
Post 3 = class 3
Post 4 = class 6
Post 5 = class 6
Post 6 = class 3
Post 7 = class 3
Post 8 = class 6
Post 9 = class 6
And so forth.
Maybe, I'm looking at it the wrong way, the $count might not even be the way to go.
Appreciate all help.
Thank you.

You can try like this, without comparing each count individually.
if( $count == 1 || $count == 4 || $count == 5) {
get_template_part( 'parts/case/item','six');
} else {
get_template_part( 'parts/case/item', 'three');
}
Or you can even try like this
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1
);
$loop = new WP_query( $args );
$count = 0;
while ( $loop->have_posts() ) : $loop->the_post();
$count++;
get_template_part( 'parts/case/item', 'somecontentpart');
?>
<?php endwhile; wp_reset_postdata();?>
then in template part's class add following code
class="<?php echo ( $count == 1 || $count == 4 || $count == 5) ? 'class6' : 'class3';?>"

Related

See last order on specific product

Hi how to see last order of specific product in woocommerce?
EXEMPLE:
PRODUCT NAME
PRICE 10 $ [ADD CART]
LAST ORDER
DATE QUT. PRICE
10.10.2021 2 9$
10.12.2021 6 3$
10.01.2022 39 5$
EDIT: I would like to place it on the product page and as a second viewer user sees his latest product orders.
Place the following function in your functions.php file
function latest_order_by_product_id() {
global $wpdb;
// Select Product ID
$product_id = 14;
$orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";
//Change get_row to get_col if you want all orders
//Change DESC to ASC if we need reverse order
$orders = $wpdb->get_row("
SELECT DISTINCT woi.order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim,
{$wpdb->prefix}woocommerce_order_items as woi,
{$wpdb->prefix}posts as p WHERE woi.order_item_id = woim.order_item_id AND woi.order_id = p.ID
AND p.post_status IN ( $orders_statuses ) AND woim.meta_key IN ( '_product_id', '_variation_id' ) AND woim.meta_value LIKE '$product_id' ORDER BY woi.order_item_id DESC");
if($orders):
$data = array();
foreach($orders as $key => $order_id):
$order = wc_get_order( $order_id );
if ( $order ):
$data[$key]['order_date'] = $order_date = $order->get_date_completed(); // Change depending on type of date you are looking for - get_date_created(), get_date_completed(), get_date_paid()
//Loop order items
foreach ( $order->get_items() as $item_id => $item ):
if($product_id == $item->get_product_id()):
$data[$key]['qty'] = $product_qty = $item->get_quantity();
//Choose which price you want to get
$data[$key]['price'] = $product_price = $item->get_total() + $item->get_total_tax(); // Discounted total with tax
//OR
//$product_price = $item->get_subtotal() + $item->get_subtotal_tax(); // NON discounted total with tax
endif;
endforeach;
endif;
endforeach;
endif;
if($data):
$output = array();
$output[] .='<table><thead><tr><th>LAST ORDER DATE</th><th>QTY</th><th>PRICE</th></tr></theead><tbody>';
foreach($data as $order_data):
//Change date format if needed
$date = $order_data['order_date']->date("d.m.Y");
$output[] .= '<tr><td>'.$date.'</td><td>'.$order_data['qty'].'</td><td>'.$order_data['price'].'</td></tr>';
endforeach;
$output[] .= '</tbody></table>';
endif;
echo sprintf('%s',implode($output));
}
Call latest_order_by_product_id() where you need it. Result - https://prnt.sc/6AhgTPXFerBg
Example with shortcode. How to use [lobpid product_id="35"]
add_shortcode('lobpid','latest_order_by_product_id' );
function latest_order_by_product_id($attr) {
global $wpdb;
$args = shortcode_atts( array(
'product_id' => '',
), $attr );
// Select Product ID
$product_id = $args['product_id'];
//Skip the rest if we dont have product id defined
if(empty($product_id)): echo 'there is no product id defined'; return; endif;
$orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";
//Change get_row to get_col if you want all orders
//Change DESC to ASC if we need reverse order
$orders = $wpdb->get_row("
SELECT DISTINCT woi.order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim,
{$wpdb->prefix}woocommerce_order_items as woi,
{$wpdb->prefix}posts as p WHERE woi.order_item_id = woim.order_item_id AND woi.order_id = p.ID
AND p.post_status IN ( $orders_statuses ) AND woim.meta_key IN ( '_product_id', '_variation_id' ) AND woim.meta_value LIKE '$product_id' ORDER BY woi.order_item_id DESC");
//Skip the rest if we dont have orders
if(empty($orders)): echo 'no orders found'; return; endif;
if($orders):
$data = array();
foreach($orders as $key => $order_id):
$order = wc_get_order( $order_id );
if ( $order ):
$data[$key]['order_date'] = $order_date = $order->get_date_completed(); // Change depending on type of date you are looking for - get_date_created(), get_date_completed(), get_date_paid()
//Loop order items
foreach ( $order->get_items() as $item_id => $item ):
if($product_id == $item->get_product_id()):
$data[$key]['qty'] = $product_qty = $item->get_quantity();
//Choose which price you want to get
$data[$key]['price'] = $product_price = $item->get_total() + $item->get_total_tax(); // Discounted total with tax
//OR
//$product_price = $item->get_subtotal() + $item->get_subtotal_tax(); // NON discounted total with tax
endif;
endforeach;
endif;
endforeach;
endif;
if($data):
$output = array();
$output[] .='<table><thead><tr><th>LAST ORDER DATE</th><th>QTY</th><th>PRICE</th></tr></theead><tbody>';
foreach($data as $order_data):
//Change date format if needed
$date = $order_data['order_date']->date("d.m.Y");
$output[] .= '<tr><td>'.$date.'</td><td>'.$order_data['qty'].'</td><td>'.$order_data['price'].'</td></tr>';
endforeach;
$output[] .= '</tbody></table>';
endif;
echo sprintf('%s',implode($output));
}

Alphabetize Wordpress taxonomy list by last name

I have a query which outputs a list of taxonomy tags, organised by FIRST NAME with an alphabetical heading, like so:
E
Elena Ferrante 
H
Helen DeWitt
J
Joan Didion
Jonathan Franzen 
K
Kazuo Ishiguro
M
Maggie Nelson
P
Plato
R
Rachel Cusk
Roberto Bolaño
S
Sheila Heti
etc.
How can I alphabetize this list of taxonomy tags by LAST NAME instead of FIRST NAME?
So the result would be:
B
Roberto Bolaño
C
Rachel Cusk
D
Helen DeWitt
Joan Didion
F
Elena Ferrante
Jonathan Franzen 
H
Sheila Heti 
I
Kazuo Ishiguro
P
Plato
N
Maggie Nelson
etc.
Here is the query:
<?php
$list = '';
$groups = array();
$tags = get_terms('authors',$args);
if( $tags && is_array( $tags ) ) {
foreach( $tags as $tag ) {
$first_letter = strtoupper( $tag->name[0] );
$groups[ $first_letter ][] = $tag;
}
if( !empty( $groups ) ) {
foreach( $groups as $letter => $tags ) {
$list .= "<div class='titleLetter'>" . $letter . "</div><ul>";
foreach( $tags as $tag ) {
$list .= '<li>'.$tag->name.'</li>';
}
$list .= '<br></ul>';
}
$list .= '';
}
}
echo $list; ?>
If the given code works for First Name ordering. Then this one will work for orderby lastname.
<?php
$list = '';
$groups = array();
$tags = get_terms('authors',$args);
if( $tags && is_array( $tags ) ) {
$i=0;
foreach( $tags as $tag ) {
$lastname_arr=explode(' ', $tag->name);
$lastname=$lastname_arr[count($lastname_arr)-1];
$first_letter = strtoupper( $lastname[0] );
$groups[ $first_letter ][$lastname.'_'.$i] = $tag;
$i++;
}
foreach($groups as $key=>$group ){
ksort($groups[$key]);
}
ksort($groups);
if( !empty( $groups ) ) {
foreach( $groups as $letter => $tags ) {
$list .= "<div class='titleLetter'>" . $letter . "</div><ul>";
foreach( $tags as $tag ) {
$list .= '<li>'.$tag->name.'</li>';
}
$list .= '<br></ul>';
}
$list .= '';
}
}
echo $list;
?>
What i did here are:
replaced array index with the first letters of lastnames.
applied ksort(sort by key) function to array and sub-arrays (in order to create custom orderby on new indexes)

Mod a Wordpress Function to have 10 iteration per times

Im tryng to mod this function to make an update more powerful.
What im tryng to do is to mod this function:
add_action( 'wp_loaded', 'cron_revise_changed_listings' );
function cron_revise_changed_listings() {
global $wpdb;
if ( !isset( $_REQUEST['wplister_revise_all'] ) ) {
return;
}
$limit = isset( $_REQUEST['revise_limit'] ) ? intval( $_REQUEST['revise_limit'] ) : 10;
$listings = $wpdb->get_results("
SELECT id, account_id
FROM {$wpdb->prefix}ebay_auctions
WHERE status = 'changed'
ORDER BY id DESC
LIMIT {$limit}", ARRAY_A );
if ( empty( $listings ) ) {
die( json_encode( array( 'revised' => 0 ) ) );
}
$lm = new ListingsModel();
$revised = 0;
$last_account_id = false;
foreach ( $listings as $listing ) {
if ( $last_account_id != $listing['account_id'] ) {
$last_account_id = $listing['account_id'];
WPLE()->initEC( $listing['account_id'] );
}
$lm->reviseItem( $listing['id'], WPLE()->EC->session );
$revised++;
}
WPLE()->EC->closeEbay();
die( json_encode( array( 'revised' => $revised ) ) );
}
What i need to obtain is to repeat cycle for each, but with a step of 10 items per time so for revise 100 items it need only to do 10 cicles and not 100...someone have any ideas?

Retrieve Wordpress 3.5 gallery images NOT attached

I am trying to find out how to use this code referencing the answer to the question here:
`global $post;
$post_subtitrare = get_post( $post->ID );
$content = $post_subtitrare->post_content;
$pattern = get_shortcode_regex();
preg_match( "/$pattern/s", $content, $match );
if( isset( $match[2] ) && ( "gallery" == $match[2] ) ) {
$atts = shortcode_parse_atts( $match[3] );
$attachments = isset( $atts['ids'] ) ? explode( ',', $atts['ids'] ) : get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . $post->ID .'&order=ASC&orderby=menu_order ID' );
}`
to retrieve the same data as the get_children()? Currently, only ids are retrieved but I have tried get_post() and get_posts().
Serialized data from the get_children array:
{i:229;O:7:"WP_Post":24:{s:2:"ID";i:229;s:11:"post_author";s:1:"1";
s:9:"post_date";s:19:"2012-12-27 21:01:49";s:13:"post_date_gmt";
s:19:"2012-12-27 21:01:49";s:12:"post_content";s:0:""
;s:10:"post_title";s:8:"DSCN0703";s:12:"post_excerpt";
s:0:"";s:11:"post_status";s:7:"inherit";
s:14:"comment_status";s:6:"closed";
s:11:"ping_status";s:4:"open";s:13:"post_password";s:0:"";
s:9:"post_name";s:10:"dscn0703-6";s:7:"to_ping";s:0:"";s:6:"pinged";s:0:"";
s:13:"post_modified";s:19:"2012-12-27 21:01:49";s:17:"post_modified_gmt";
s:19:"2012-12-27 21:01:49";s:21:"post_content_filtered";s:0:"";
s:11:"post_parent";i:223;s:4:"guid";s:81:"http:/exampleurl.com/wp-content/uploads/2012/12/DSCN07031.jpg";s:10:"menu_order";i:1;s:9:"post_type";s:10:"attachment";s:14:"post_mime_type";s:10:"image/jpeg";s:13:"comment_count";s:1:"0";s:6:"filter";s:3:"raw";}
Serialized data from the code:
a:7:{i:0;s:3:"229";i:1;s:3:"225";i:2;s:3:"228";i:3;s:3:"230";i:4;s:3:"226";i:5;s:3:"227";i:6;s:3:"232";}
Can someone point me to the wp hook that will give me the same data as the get_children from the ids generated from the above code?
Not 100% sure what you're after but this is a copy of the code I used ( based on that answer with some additions ) ... it may help
$post_subtitrare = get_post( $post->ID );
$content = $post_subtitrare->post_content;
$pattern = get_shortcode_regex();
preg_match( "/$pattern/s", $content, $match );
if ( isset( $match[2] ) && ( "gallery" == $match[2] ) ) {
$atts = shortcode_parse_atts( $match[3] );
$images = isset( $atts['ids'] ) ? explode( ',', $atts['ids'] ) : get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . $post->ID .'&order=ASC&orderby=menu_order ID' );
}
if ( $images ) :
$first_element = array_shift(array_values($images));
if ( ! is_object($first_element)) {
$image_count = count( $images );
$first_image = $images[0];
$featured = wp_get_attachment_image( $first_image, 'blog-featured-image' );
}
else {
$image_count = count( $images );
$first_image = array_shift(array_values($images));
$imageID = $first_image->ID;
$featured = wp_get_attachment_image( $imageID, 'blog-featured-image' );
}
... this gave me some variables which I could use including $featured.

Break Up WordPress Archive List into Multiple Columns

I want to break up this archive list into multiple columns (three columns)...I don't want to use CSS3 for this. I can easily do this with wp_list_categories, but that method doesn't work with wp_get_archives.
Ideally, I'd like to implement a counter to add in tags at an approximate 1/3 count...then I can use CSS for the rest.
CUSTOM ARCHIVE FUNCTION:
function wp_custom_archive($args = '') {
global $wpdb, $wp_locale;
$defaults = array(
'limit' => '',
'format' => 'html', 'before' => '',
'after' => '', 'show_post_count' => false,
'echo' => 1
);
$r = wp_parse_args( $args, $defaults );
extract( $r, EXTR_SKIP );
if ( '' != $limit ) {
$limit = absint($limit);
$limit = ' LIMIT '.$limit;
}
// over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
$archive_date_format_over_ride = 0;
// options for daily archive (only if you over-ride the general date format)
$archive_day_date_format = 'Y/m/d';
// options for weekly archive (only if you over-ride the general date format)
$archive_week_start_date_format = 'Y/m/d';
$archive_week_end_date_format = 'Y/m/d';
if ( !$archive_date_format_over_ride ) {
$archive_day_date_format = get_option('date_format');
$archive_week_start_date_format = get_option('date_format');
$archive_week_end_date_format = get_option('date_format');
}
//filters
$where = apply_filters('customarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r );
$join = apply_filters('customarchives_join', "", $r);
$output = '<ul>';
$query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC $limit";
$key = md5($query);
$cache = wp_cache_get( 'wp_custom_archive' , 'general');
if ( !isset( $cache[ $key ] ) ) {
$arcresults = $wpdb->get_results($query);
$cache[ $key ] = $arcresults;
wp_cache_set( 'wp_custom_archive', $cache, 'general' );
} else {
$arcresults = $cache[ $key ];
}
if ( $arcresults ) {
$afterafter = $after;
foreach ( (array) $arcresults as $arcresult ) {
$url = get_month_link( $arcresult->year, $arcresult->month );
/* translators: 1: month name, 2: 4-digit year */
$text = sprintf(__('%s'), $wp_locale->get_month($arcresult->month));
$year_text = sprintf('<li>%d</li>', $arcresult->year);
if ( $show_post_count )
$after = ' ('.$arcresult->posts.')' . $afterafter;
$output .= ( $arcresult->year != $temp_year ) ? $year_text : '';
$output .= get_archives_link($url, $text, $format, $before, $after);
$temp_year = $arcresult->year;
}
}
$output .= '</ul>';
if ( $echo )
echo $output;
else
return $output;
}
CURRENT HTML OUTPUT (shortened):
<ul>
<li>2012</li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/09/' title='September'>September</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/08/' title='August'>August</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/07/' title='July'>July</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/06/' title='June'>June</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/05/' title='May'>May</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/04/' title='April'>April</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/03/' title='March'>March</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/02/' title='February'>February</a></li>
<li><a href='http://alittlesewing.com.s118336.gridserver.com/2012/01/' title='January'>January</a></li>
</ul>
If I understand correctly, you would have to do something like this
$output = '<ul class="col1">';
if ( $arcresults ) {
$numarticles = count($arcresults);
$column1 = round($numarticles/3);
$column2 = round($column1*2);
$counter = 0;
$afterafter = $after;
foreach ( (array) $arcresults as $arcresult ) {
if($counter == $column1) {
$output .= "</ul><ul class='col2'>";
} elseif($counter == $column2) {
$output .= "</ul><ul class='col3'>";
}
$url = get_month_link( $arcresult->year, $arcresult->month );
/* translators: 1: month name, 2: 4-digit year */
$text = sprintf(__('%s'), $wp_locale->get_month($arcresult->month));
$year_text = sprintf('<li>%d</li>', $arcresult->year);
if ( $show_post_count )
$after = ' ('.$arcresult->posts.')' . $afterafter;
$output .= ( $arcresult->year != $temp_year ) ? $year_text : '';
$output .= get_archives_link($url, $text, $format, $before, $after);
$temp_year = $arcresult->year;
$counter ++;
}
$output .= '</ul>';
}
This way, when the counter gets to a third of the way, it will add another list, so at the end you will have 3 lists.
Hope this helps.

Resources