Targeting last item in foreach loop problem - wordpress

I'm trying to target the last item in a foreach loop but it's acting a little strange.
I've got two items in the loop, I've tried the following:
Not set a +/- for the count, this targets the first item.
Using -1 as the count also targets the first item.
Using +1 as the count doesn't target any items until you add a 3rd
item, then it works as intended.
Here's the code, can anyone help?
<?php $pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order'));
foreach($pages as $key => $post)
{
setup_postdata($post);
$fields = get_fields();
?>
<div class="event<?php if( $key == (count( $pages ) +1) ) echo 'last'; ?>">
</div>
<?php } wp_reset_query(); ?>

This is the way to do it:
<?php
$pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order'));
// keep a record of the number of pages -1
// in order to compare against 0 indexed array key
$pagesNo = count($pages)-1;
foreach($pages as $key => $post)
{
setup_postdata($post);
$fields = get_fields();
?>
<div class="event<?php if( $key == $pagesNo ) echo 'last'; ?>"></div>
<?php } wp_reset_query(); ?>

When you need to count, a for or while loop might be a better than foreach.

Related

How to get_children and their grand children

How to get grand-childrens of children of a page?
<?php
global $post;
$pages = get_children(array(
'post_parent' => $post->ID,
'numberposts' => -1
));
if ( $pages ):
$rows = array_chunk( $pages, ceil( count($pages) / 3 ) ); ?>
<div class="row">
<?php foreach ( $rows as $row ): ?>
<div class="col-sm-4">
<ul class="list-unstyled">
<?php foreach ( $row as $city ): ?>
<li><?= $city->post_title ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
</div>
<?php endif;
by using wp_list_pages I can't make columns for my list
Shows children page links on both parent and child pages.
<?php
global $post;
// Use parent page if exists, else use current page
$child_of_value = ( $post->post_parent ? $post->post_parent : $post->ID );
// Depth of 2 if parent page, else depth of 1
$depth_value = ( $post->post_parent ? 2 : 1 );
// Build argument array
$wp_list_pages_args = array(
'child_of' => $child_of_value,
'depth' => $depth_value,
'title_li' => 'Sections',
'echo' => 0
);
// Now, output the result
wp_list_pages( $wp_list_pages_args );
?>

wordpress if get_categories value larger/smaller

i have code in category.php
<?php $getcatid = get_query_var('cat'); ?>
<?php $args = array('child_of' => ''.$getcatid.'', 'parent' => ''.$getcatid.'', 'hide_empty' => 0);?>
<?php $categories = get_categories($args); foreach ($categories as $cat) { ?>
<?php $getid = $cat->cat_ID; ?>
how to check quantity subcategory value as:
if $categories < 4 ($getcatid had smaller 4 sub) echo code loop
else (if $categories > 4 ) echo code loop
Any idea. Thanks
If you retrieve your categories with get_categories you can easily run count() on the result, to check how many entries there are. You can then use that number for your comparison.
Probably like this (untested):
<?php
// stripped your code out
$categories = get_categories($args);
if(count($categories) > 4) { }
else { }
?>

Custom parent category and subcategory

I really need your help. i just created a WordPress page template that display all the post but my problem is the display of the custom parent taxonomy/category and it's children. My post look like this.
<table>
<tr>
<td>Title</td>
<td>Parent Category</td>
<td>Sub Category</td>
<td>Excerpt</td>
</tr>
<tr>
<td>a title</td>
<td>USA custom category</td>
<td>Hawaii uder USA</td>
<td>this is a sample description.</td>
</tr>
</table>
My only problem is to display the sub category. Anyone can help me?
This is my code on how i display the parent custom category:
<?php
$term_list = '';
$terms = get_the_terms( $post->ID, 'origincity' );
foreach( $terms as $term ) {
$parent_term = get_term( $term->parent, 'origincity' );
$term_list .= $parent_term->name ;
}
echo $term_list;
?>
I tried to display the sub category by this code :
<?php $terms2 = wp_get_post_terms($post->ID, 'origincity', array("fields" => "all"));
foreach ($terms2 as $term1) {
echo $term1->name.'<br>';
} ?>
but it also return the parent. :(
Your help is highly appreciated. Thanks.
I dont suggest using your method you are currently using because you don't have enough control over what's showing.
In future use get_posts();
It's really simple to use! For example:
<ul>
<?php
global $post;
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li>
<?php the_title(); ?>
</li>
<?php endforeach; ?>
</ul>
As you can see you can set how many posts, the category and many more arguments for the posts displayed.
Find out more about the arguments here http://codex.wordpress.org/Template_Tags/get_posts
Already solve the problem by this code:
function print_taxonomic_ranks( $terms ){
// set id variables to 0 for easy check
$order_id = $family_id = $subfamily_id = 0;
// get family
foreach ( $terms as $term ) {
if ( $family_id || $order_id != $term->parent )
continue;
$family_id = $term->term_id;
$family = $term->name;
}
// get subfamily
foreach ( $terms as $term ) {
if ( $subfamily_id || $family_id != $term->parent )
continue;
$subfamily_id = $term->term_id;
$subfamily = $term->name;
}
// output
echo "$subfamily";
}
Thanks by the way.

Making custom WooCommerce loop

I'm using already designed theme for wordpress, and now instead of regular blog posts I would like to display WooCommerce products (which are custom post types I persume).
This is the current query with display loop:
<?php
$args = array(
//'posts_per_page' => '2',
'paged' => get_query_var('paged')
);
$homepage_query = new WP_Query($args);
?>
<?php //query_posts('posts_per_page=4&paged='.get_query_var('paged')); ?>
<?php if ( have_posts() ) : ?>
<?php while ( $homepage_query->have_posts() ) : $homepage_query->the_post(); ?>
<?php if($style == 'blog_style') { ?>
<div id="blog-style" class="post-box">
<?php get_template_part('content', 'blog'); ?>
</div>
<?php } else { ?>
<div class="post-box grid_4 <?php aero_post_box_class(); ?>">
<?php get_template_part('content', ''); ?>
</div>
<?php } ?>
<?php endwhile; ?>
Is there a way to add options to $args so the loop displays WooCommerce products? I'm also using pagination with this loop, which is required on this project, so that's why it's important to use this loop.
You should be able to access products through the loop, setting the post_type arg to product:
<?php
// Setup your custom query
$args = array( 'post_type' => 'product', ... );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php echo get_permalink( $loop->post->ID ) ?>">
<?php the_title(); ?>
</a>
<?php endwhile; wp_reset_query(); // Remember to reset ?>
This is the proper way to re-create and customize the WooCommerce product loop:
if(!function_exists('wc_get_products')) {
return;
}
$paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1; // if your custom loop is on a static front page then check for the query var 'page' instead of 'paged', see https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters
$ordering = WC()->query->get_catalog_ordering_args();
$ordering['orderby'] = array_shift(explode(' ', $ordering['orderby']));
$ordering['orderby'] = stristr($ordering['orderby'], 'price') ? 'meta_value_num' : $ordering['orderby'];
$products_per_page = apply_filters('loop_shop_per_page', wc_get_default_products_per_row() * wc_get_default_product_rows_per_page());
$products_ids = wc_get_products(array(
'status' => 'publish',
'limit' => $products_per_page,
'page' => $paged,
'paginate' => true,
'return' => 'ids',
'orderby' => $ordering['orderby'],
'order' => $ordering['order'],
));
wc_set_loop_prop('current_page', $paged);
wc_set_loop_prop('is_paginated', wc_string_to_bool(true));
wc_set_loop_prop('page_template', get_page_template_slug());
wc_set_loop_prop('per_page', $products_per_page);
wc_set_loop_prop('total', $products_ids->total);
wc_set_loop_prop('total_pages', $products_ids->max_num_pages);
if($products_ids) {
do_action('woocommerce_before_shop_loop');
woocommerce_product_loop_start();
foreach($products_ids->products as $featured_product) {
$post_object = get_post($featured_product);
setup_postdata($GLOBALS['post'] =& $post_object);
wc_get_template_part('content', 'product');
}
wp_reset_postdata();
woocommerce_product_loop_end();
do_action('woocommerce_after_shop_loop');
} else {
do_action('woocommerce_no_products_found');
}
Using the code above, you would customize the wc_get_products() arguments to get the IDs of the products you want (if you have specific criteria). Once that code is in place, all the features of a native WooCommerce loop will be available to you—pagination, ordering, etc. This method is superior to WP_Query and get_posts() because those two methods can break.
I've written a more detailed blog post about custom WooCommerce loops here: https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/
You can Also get Category using thi code
$terms = get_terms('product_cat');
foreach ($terms as $term) {
$term_link = get_term_link( $term, 'product_cat' );
echo '<li>' . $term->name . '</li>';
}
If You want only parent category then
wp_list_categories('taxonomy=product_cat&orderby=order&title_li=&depth=1');

Why doesn't get_post_custom() work within the loop in WordPress?

I've created a custom post type in WordPress, and in the single post template, I'm successfully pulling in my custom data using the get_post_custom() function.
But inside The Loop on the list of posts, the function doesn't work and comes back with an empty array.
Here's what I have:
<?php $loop = new WP_Query( array( 'post_type' => 'web-design', 'posts_per_page' => 10 ) ); ?>
<?php $i = 0; ?>
<?php while ( $loop->have_posts() && $i < 3 ) { $loop->the_post(); ?>
<article class="project-link <?php echo 'num' . $i ?>">
<div class="pad">
<?php $project_info = get_post_custom(); ?>
<?php
foreach ($project_info as $i => $values) {
print "$i {\n";
foreach ($values as $key => $value) {
print "$key => $value\n";
}
print "}\n";
}
?>
<?php echo $project_info['url'][0]; ?>
And I don't have anything coming back at all.
Does anyone know why this doesn't work? It works fine in the single post template, why not in the loop?
Thanks!
the post_custom() has many variables stored in arrays ..
if you know the specific key , or value that you need you can use
or just itirate through them like this :
<?php
$mykey_values = get_post_custom_values('my_key');
foreach ( $mykey_values as $key => $value ) {
echo "$key => $value ('my_key')<br />";
}
?>
or for a specific post
<?php
$custom_fields = get_post_custom(72);
$my_custom_field = $custom_fields['my_custom_field'];
foreach ( $my_custom_field as $key => $value )
echo $key . " => " . $value . "<br />";
?>
It seems as though the problem lies with the database. I noticed that if I deleted certain posts, then it would start working fine. I'm yet to find out what's wrong with these posts though, if I delete them and then re-create them, they're usually fine.
My advice to anyone with this problem is try moving some of your posts to the trash and see if it starts working.

Resources