Categories and Sub Categories in custom taxonomies - wordpress

I find and use the following code to display sub categories for default taxonomy 'category' on my site, but I created a custom taxonomy , and can not alter the code so that he was doing the same thing for the new taxonomy, help please
<?php
if(is_category()) {
$subcategories = get_terms('category', 'parent='.get_query_var('cat'));
if(empty($subcategories)) {
$thiscat = get_term(get_query_var('cat'),'category');
$subcategories = get_terms('category', 'parent='.$thiscat->parent.'');
}
if(empty($subcategories)) $subcategories = array();
if(!empty($subcategories)) {
echo '<ul>';
foreach($subcategories as $subcat) {
if(get_query_var('cat') == $subcat->term_id) $current = ' current-cat'; else $current = '';
echo '
<li class="cat-item cat-item-'.$subcat->term_id.$current.'">
'.$subcat->name.'
</li>';
}
echo '</ul>';
}
}
else {
// If no current cat query, just get the top level ones using wp_list_categories.
?>
<ul>
<?php wp_list_categories('title_li=&depth=1');?>
</ul>
<?php
}
?>

It turned out, the code works as I wanted, but if it can be optimize I'll be glad to help ... This code displays the subcategories to the main categories of taxonomies.
If anyone should use, just change 'auto' to the name of your taxonomy. my custom taxonomy is 'auto'
<?php
if(is_tax()) {
$subcategories = get_terms('auto', 'parent='.get_queried_object()->term_id);
if(empty($subcategories)) {
$thiscat = get_term(get_queried_object()->term_id,'auto');
$subcategories = get_terms('auto', 'parent='.$thiscat->parent.'');
}
if(empty($subcategories)) $subcategories = array();
if(!empty($subcategories)) {
echo '<ul>';
foreach($subcategories as $subcat) {
if(get_queried_object()->term_id == $subcat->term_id) $current = ' current-cat'; else $current = '';
echo '
<li class="cat-item cat-item-'.$subcat->term_id.$current.'">
'.$subcat->name.'
</li>';
}
echo '</ul>';
}
}
else {
// If no current cat query, just get the top level ones using wp_list_categories.
?>
<ul>
<?php wp_list_categories('taxonomy=auto&title_li=&depth=1');?>
</ul>
<?php
}
?>

Thanks for the corrected code.
I have added a bit for people who want to exit of the loop once they come to any end. Instead of showing the parent categories tree i modified a bit to display the image and title of the of the products or services under that specific category. Following is the code
if(is_tax()) {
$subcategories = get_terms('product_categories', 'parent='.get_queried_object()->term_id);
// this is the change which display all the products in the specific category if it does not have child categories
if(empty($subcategories)) {
$thiscat = get_term(get_queried_object()->term_id,'product_categories');
if (have_posts('thiscat')):while (have_posts('thiscat')) : the_post('thiscat');{?>
<div class="box cat-item-<?php $subcat->name.$current ;?>" style="min-height: 231px; margin-bottom:10px">
<?php the_post_thumbnail('thumbnail');?>
<h5><a title="<?php the_title(); ?>" href="<?php the_permalink($post->ID); ?>"><?php the_title(); ?></a></h5></h5></div>
<?php }
endwhile;
else : {
?>
<div class="box cat-item cat-item-<?php $subcat->name.$current; ?>" style="min-height: 231px; margin-bottom:10px">
<h5>Products will be upadated later. Do visit Later </h5 >
</div>
<?php }
endif;
}
if(empty($subcategories)) $subcategories = array();
if(!empty($subcategories)) {
echo '<div class="fixed-row clearfix dynamic-fixedRow-735" id="row_order_2">';
foreach($subcategories as $subcat) {
if(get_queried_object()->term_id == $subcat->term_id) $current = ' current-cat'; else $current = '';
echo '
<div class="box cat-item cat-item-'.$subcat->name.$current.'" style="min-height: 231px; margin-bottom:10px"><h5>
'.$subcat->name.'
</h5></div>';
}

Related

Woocommerce Custom shop page with infinte load

Hi currently I am creating a woocommerce custom shop page template .
For this, I have created a new template inside my theme page called custom-shop & I have created new page called my shop and assign custom-shop template.
I have 3 main category called car , bus, boat . Now I am going to display each category with its description and product details
So I write the following code in my cutom-shop template(custom-shop.php)
custom-shop.php
/*
Template name: custom-shop
*/
BLOCKS OF CODE
<div class="category-block">
<h2>Car</h2>
<p class="description">Car Description</p>
<?php echo do_shortcode('[products limit="40" columns="4" category="car"]'); ?>
</div>
<div class="category-block">
<h2>Bus</h2>
<p class="description">Bus Description</p>
<?php echo do_shortcode('[products limit="40" columns="4" category="bus"]'); ?>
</div>
<div class="category-block">
<h2>Boat</h2>
<p class="description">Boat Description</p>
<?php echo do_shortcode('[products limit="40" columns="4" category="boat"]'); ?>
</div>
Here Everything is working fine . But the problem is the page load time is high , because every product is loading together . How can i solve this issue , how can i implement infinite load ?
What I need is first display car and it's 4 products then user scroll down display other products in car . After car products finished then display bus and it's 4 products , like this
what I tried is
After searching I found a plugin https://wordpress.org/plugins/ajax-load-more/ and i t help to resolve some issue and i used this plugin code
<div class="category-block">
<h2>Car</h2>
<p class="description">Car Description</p>
<?php do_shortcode('[ajax_load_more post_type="product" columns="4" css_classes="products" posts_per_page="4" transition="fade" taxonomy="product_cat" taxonomy_terms="car" taxonomy_operator="IN" button_label=""]'); ?>
</div>
<div class="category-block">
<h2>Bus</h2>
<p class="description">Bus Description</p>
<?php do_shortcode('[ajax_load_more post_type="product" columns="4" css_classes="products" posts_per_page="4" transition="fade" taxonomy="product_cat" taxonomy_terms="car" taxonomy_operator="IN" button_label=""]'); ?>
</div>
<div class="category-block">
<h2>Car</h2>
<p class="description">Boat Description</p>
<?php do_shortcode('[ajax_load_more post_type="product" columns="4" css_classes="products" posts_per_page="4" transition="fade" taxonomy="product_cat" taxonomy_terms="car" taxonomy_operator="IN" button_label=""]'); ?>
</div>
But here the problem is that when I scroll down it will first show car and it's 4 products , then bus and it's 4 products again load other products for car . So it's not also proper solution .
Please help , to solve this issue .
actually if you want to do it by yourself, I will just suggest you to follow this guide, cmmon click me! -> It will be lots more helpful than any huge reply in here.
This guy goes trough all the ajax proceses that you will need to use. Also you can just parse a piece of his code and get it all done. Shortly, you just need ajax. more explicit -> you can see in this video
I will paste in here the code result of the guide bypassing all the small procedures for a better understanding
First of all he created a template to output the content wich looks like this
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header text-center">
<?php the_title( '<h1 class="entry-title">', '</h1>'); ?>
<div class="entry-meta">
<?php echo sunset_posted_meta(); ?>
</div>
</header>
<div class="entry-content">
<?php if( sunset_get_attachment() ): ?>
<a class="standard-featured-link" href="<?php the_permalink(); ?>">
<div class="standard-featured background-image" style="background-image: url(<?php echo sunset_get_attachment(); ?>);"></div>
</a>
<?php endif; ?>
<div class="entry-excerpt">
<?php the_excerpt(); ?>
</div>
<div class="button-container text-center">
<?php _e( 'Read More' ); ?>
</div>
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php echo sunset_posted_footer(); ?>
</footer>
</article>
Next step was to validate in wp the ajax function
add_action( 'wp_ajax_nopriv_sunset_load_more', 'sunset_load_more' );
add_action( 'wp_ajax_sunset_load_more', 'sunset_load_more' );
function sunset_load_more() {
$paged = $_POST["page"]+1;
$prev = $_POST["prev"];
$archive = $_POST["archive"];
if( $prev == 1 && $_POST["page"] != 1 ){
$paged = $_POST["page"]-1;
}
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'paged' => $paged
);
if( $archive != '0' ){
$archVal = explode( '/', $archive );
$type = ( $archVal[1] == "category" ? "category_name" : $archVal[1] );
$args[ $type ] = $archVal[2];
$page_trail = '/' . $archVal[1] . '/' . $archVal[2] . '/';
} else {
$page_trail = '/';
}
$query = new WP_Query( $args );
if( $query->have_posts() ):
echo '<div class="page-limit" data-page="' . $page_trail . 'page/' . $paged . '">';
while( $query->have_posts() ): $query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
echo '</div>';
else:
echo 0;
endif;
wp_reset_postdata();
die();
}
function sunset_check_paged( $num = null ){
$output = '';
if( is_paged() ){ $output = 'page/' . get_query_var( 'paged' ); }
if( $num == 1 ){
$paged = ( get_query_var( 'paged' ) == 0 ? 1 : get_query_var( 'paged' ) );
return $paged;
} else {
return $output;
}
}
And the last step will be the AJAX function itself.
/* Ajax functions */
$(document).on('click','.sunset-load-more:not(.loading)', function(){
var that = $(this);
var page = $(this).data('page');
var newPage = page+1;
var ajaxurl = that.data('url');
var prev = that.data('prev');
var archive = that.data('archive');
if( typeof prev === 'undefined' ){
prev = 0;
}
if( typeof archive === 'undefined' ){
archive = 0;
}
that.addClass('loading').find('.text').slideUp(320);
that.find('.sunset-icon').addClass('spin');
$.ajax({
url : ajaxurl,
type : 'post',
data : {
page : page,
prev : prev,
archive : archive,
action: 'sunset_load_more'
},
error : function( response ){
console.log(response);
},
success : function( response ){
if( response == 0 ){
$('.sunset-posts-container').append( '<div class="text-center"><h3>You reached the end of the line!</h3><p>No more posts to load.</p></div>' );
that.slideUp(320);
} else {
setTimeout(function(){
if( prev == 1 ){
$('.sunset-posts-container').prepend( response );
newPage = page-1;
} else {
$('.sunset-posts-container').append( response );
}
if( newPage == 1 ){
that.slideUp(320);
} else {
that.data('page', newPage);
that.removeClass('loading').find('.text').slideDown(320);
that.find('.sunset-icon').removeClass('spin');
}
revealPosts();
}, 1000);
}
}
});
});
/* scroll function */
$(window).scroll( function(){
var scroll = $(window).scrollTop();
if( Math.abs( scroll - last_scroll ) > $(window).height()*0.1 ) {
last_scroll = scroll;
$('.page-limit').each(function( index ){
if( isVisible( $(this) ) ){
history.replaceState( null, null, $(this).attr("data-page") );
return(false);
}
});
}
});
/* helper functions */
function revealPosts(){
var posts = $('article:not(.reveal)');
var i = 0;
setInterval(function(){
if( i >= posts.length ) return false;
var el = posts[i];
$(el).addClass('reveal').find('.sunset-carousel-thumb').carousel();
i++
}, 200);
}
function isVisible( element ){
var scroll_pos = $(window).scrollTop();
var window_height = $(window).height();
var el_top = $(element).offset().top;
var el_height = $(element).height();
var el_bottom = el_top + el_height;
return ( ( el_bottom - el_height*0.25 > scroll_pos ) && ( el_top < ( scroll_pos+0.5*window_height ) ) );
}
});
I would suggest you to follow the guide created by alecadd because it will be much easier to understand the process and suit it for your purposes. Hope it's enough now!
Cheers.

using wp_get_attachment_image_src in foreach loop

I have 10 images added to a post via Advanced Custom Fields, they're named from 1 to 10 e.g 'image_*', ACF is set to return the ID.
I'm trying to get the full size image URL of each image in the loop and use it as a href attribute to open a full size popup of the image, however I don't understand how wp_get_attachment_image_src works.
Since I am unable to use Advanced Custom Field's Repeater, this is the loop i'm using to get an array of the images with a custom image size of scaled, it works fine to generate the responsive image markup that I need:
// args
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array
for($x = 1; $x <= 10; $x++) {
$img = get_field('image_' . $x);
if($img) {
$images[] = $img;
} else {
break;
}
}
<?php foreach($images as $image) { ?>
<a href="" class="open-viewer">
<?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>
</a>
<?php } ?>
I need to set the href attribute of the parent a element with the URL of the image. This is what I have tried with wp_get_attachment_image_src, it doesn't work, it sets every href with image_10's URL.
// args
$sizeFull = 'full'; // full size image
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array
for($x = 1; $x <= 10; $x++) {
$img = get_field('image_' . $x);
$image_array = wp_get_attachment_image_src($img, $sizeFull);
$link = $image_array[0];
if($img) {
$images[] = $img;
} else {
break;
}
}
<?php foreach($images as $image) { ?>
<a href="<?php echo $link; ?>" class="open-viewer">
<?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>
</a>
<?php } ?>
My question is: How can I set the href of a.open-viewer with the correct URL?, and secondly, why does my code fail? (debug is switched on but no errors appear).
I realise I've horribly misunderstood something here, I'm a PHP novice so any advice about my approach would be appreciated.
In your first block, in your loop, you're setting the value of $link to the value of $image_array[0], but you're overwriting it each time. You want array_push here.
$images = array();
for($x = 1; $x <= 10; $x++) {
$img = get_field('image_' . $x);
$image_array = wp_get_attachment_image_src($img, $sizeFull);
if($image_array && $image_array[0]) {
array_push($images,
array(
src => $image_array[0],
id => $img
)
);
} else {
break;
}
}
Now, when you loop over it the second array, you can just do:
<?php foreach($images as $image) { ?>
<a href="<?php echo $image['src']; ?>" class="open-viewer">
<?php echo wp_get_attachment_image( $image['id'], $sizeHuge ); ?>
</a>
<?php } ?>
And the value of href should be the image URL.
Following is the updated/corrected code which will work for you:
<?php
// args
$sizeFull = 'full'; // full size image
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array
for($x = 1; $x <= 10; $x++) {
$img = get_field('image_' . $x);
if($img) {
$images[] = $img;
} else {
break;
}
}
<?php foreach($images as $image) {
$image_array = wp_get_attachment_image_src($image, $sizeFull);
$link = $image_array[0];
?>
<a href="<?php echo $link; ?>" class="open-viewer">
<?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>
// or Rather than calling above function, why don't you write <img> tag as you already have image url ? Like:
<img src="<?php echo $link; ?>" class="">
</a>
<?php } ?>

Modifying Wordpress plugin

i have a trouble with plugin, script reads the first characters (A,B,C.. from letters) but if it is Č (or different language special characters) wrotes "Sorry, no posts were found!"
here is a screen:
http://postimg.org/image/m8lfc04uj/
please advise where is the problem,thank you
<?php query_posts('post_parent=83&post_type=page&post_status=publish&orderby=title&order=ASC'); ?>
<?php if ( have_posts() ) {
$in_this_row = 0;
while ( have_posts() ) {
the_post();
$first_letter = mb_strtoupper(substr(apply_filters('the_title',$post->post_title),0,1));
if ($first_letter != $curr_letter) {
if (++$post_count > 1) {
end_prev_letter();
}
start_new_letter($first_letter);
$curr_letter = $first_letter;
}
if (++$in_this_row > $posts_per_row) {
end_prev_row();
start_new_row();
++$in_this_row; // Account for this first post
} ?>
<div class="title-cell"><?php the_title(); ?></div>
<?php }
end_prev_letter();
?>
<div class="navigation">
<div class="alignleft"><?php next_posts_link('« Higher Letters') ?></div>
<div class="alignright"><?php previous_posts_link('Lower Letters »') ?></div>
</div>
<?php } else {
echo "<h2>Sorry, no posts were found!</h2>";
}
?>
<?php
function end_prev_letter() {
end_prev_row();
echo "</div><!-- End of letter-group -->\n";
// echo "<div class='clear'></div>\n";
}
function start_new_letter($letter) {
echo "<div class='letter-group'>\n";
echo "\t<div class='letter-cell'>$letter</div>\n";
start_new_row($letter);
}
function end_prev_row() {
echo "\t</div><!-- End row-cells -->\n";
}
function start_new_row() {
global $in_this_row;
$in_this_row = 0;
echo "\t<div class='row-cells'>\n";
}
?>
Try replacing the line:
$first_letter = mb_strtoupper(substr(apply_filters('the_title',$post->post_title),0,1));
..with:
$first_letter = mb_strtoupper(substr(apply_filters('the_title',$post->post_title),0,1), 'UTF-8');
This should make it work with non-latin characters.

Get thumbnail from page? (Concrete 5.7.4.2)

As posted here https://www.concrete5.org/index.php?cID=751287 I want to get a thumbnail from a page using the 'old' way.
Before I could use the code below which included an image helper.
<div class="image-link">
<a <?php if ($target != '') { ?> target="<?php echo $target ?>" <?php } ?> href="<?php echo $url ?>">
<?php
$ts = $page->getBlocks('Thumbnail Image');
if (is_object($ts[0])) {
$tsb = $ts[0]->getInstance();
$thumb = $tsb->getFileObject();
if ($thumb) {
$ih->outputThumbnail($thumb, 170, 80, $title);
}
}
?>
</a>
</div>
From this section of the subpage:
<div id="thumbnail">
<?php
if ($c->isEditMode()) {
print '<br><br>';
$a = new Area('Thumbnail Image');
$a->display($c);
}
?>
</div>
However now this has all changed and the new system uses page attributes for thumbnails. As the site is already setup the 'old' way I want to be able to retrieve the thumbnail the same way again.
Any help would be much appreciated.
I have "thumbnail" page attribute set via the composer, and this is how I retrieve it in the page template:
<?php
$thumbnail = $c->getAttribute('thumbnail');
if($thumbnail) {
$img = Core::make('html/image', array($thumbnail));
$tag = $img->getTag();
print $tag;
}
?>
I dug out my experimentation hat and fixed it.
<div class="image-link">
<a <?php if ($target != '') { ?> target="<?php echo $target ?>" <?php } ?> href="<?php echo $url ?>">
<?php
foreach ($blocks as $block) {
if ($block->getBlockTypeHandle() == "image" && $block->getAreaHandle() == "Thumbnail Image") {
if (is_object($block)) {
$tsb = $block->getInstance();
$thumb = $tsb->getFileObject();
if ($thumb) {
$ih->outputThumbnail($thumb, 170, 80);
}
}
}
}
?>
</a>
</div>

Add active class to the menu item - not menu created with wordpress, custom menu

I have a menu created with this code
<?php
$pages = get_pages('child_of= 8&sort_column=post_date&sort_order=asc&parent=8');
foreach($pages as $page) {
?>
<li><a href="<?php $permalink = get_permalink($page->ID);
echo $permalink ; ?>"><?php echo $page->post_title ?></a></li>
<?php } ?>
With this I got the Child Pages of Main about Page. And I need to add active class in this items depending on which page i am(menu created with code above).
You can do that simply by use is_page() to test if the user visit the active page in your menu :
<?php
$pages = get_pages('child_of= 8&sort_column=post_date&sort_order=asc&parent=8');
foreach ( $pages as $page ) {
if ( is_page( $page->ID ) ) {
$active = 'class="active"';
} else {
$active = '';
}
echo '<li '.$active.'>'.$page->post_title.'</li>';
}
?>
Add this in your <li> (or <a>, as you wish) tag:
<?php if ( get_the_ID() == $page->ID ) echo ' class="active"'; ?>
You will want to use the following line inside class=''
If(get_the_ID()==$page->ID) echo 'class="active"';

Resources