I have this function working great
<?php
$categories = get_categories(array(
'hide_empty' => 0,
'taxonomy' => 'category',
'orderby' => 'title',
'order' => 'ASC'
));
foreach ($categories as $category) {
$firstletter = strtoupper(substr($category->name,0,1));
$link = get_category_link( $category->term_id );
if ($firstletter != $current) {
$postlist .= "<b><a name='$firstletter'> $firstletter </a></b><br>\n";
$nav .= "<a href='#$firstletter'> $firstletter </a> ";
$current = $firstletter;
}
$postlist .= "<a href='$link'>" . $category->cat_name . "</a><br>\n";
}
print $nav . "<br>" . $postlist;
?>
What I need, is to wrap the entire list starting with the letter. For example, Letter M will be wrapped in a div with all the categories starting with M.
This is what I currently get: http://i.imgur.com/PEmJw03.png - Any help would be appreciated, thank you.
You seem to be on the right path. I think this is what you are requesting to do:
$closeLastDiv = false;
foreach ($categories as $category) {
$firstletter = strtoupper(substr($category->name,0,1));
$link = get_category_link( $category->term_id );
if ($firstletter != $current) {
if ($firstletter == ""){ //first time through
$postlist .= "<div>";
$closeLastDiv = true;
} else {
$postlist .= "</div><div>";
}
$postlist .= "<b><a name='$firstletter'> $firstletter </a></b><br>\n";
$nav .= "<a href='#$firstletter'> $firstletter </a> ";
$current = $firstletter;
}
$postlist .= "<a href='$link'>" . $category->cat_name . "</a><br>\n";
}
if ($closeLastDiv) {
$postlist .= "</div>";
}
All you need is comparte the current letter with before letter, and if changed print the starting wrapper + content. When the letter changes, close the wrapper and open the next wraper.
Something like this:
$current = "-";
$postlist .= "<div>";
foreach ($categories as $category) {
$firstletter = strtoupper(substr($category->name,0,1));
$link = get_category_link( $category->term_id );
if ($firstletter != $current) {
$postlist .= "</div><div id='{$firstletter}'>";
$postlist .= "<b><a name='{$firstletter}'>".$firstletter."</a></b><br>\n";
$nav .= "<a href='#{$firstletter}'>".$firstletter."</a> ";
$current = $firstletter;
}
$postlist .= "<a href='$link'>" . $category->cat_name . "</a><br>";
}
$postlist .= "</div>";
The first div remain empty, but all other are ok.
Related
I have a page where all my WP posts are displayed. The category of the post displays fine but when I try to also display the taxonomy, it doesn't work.
This is working :
<span><i class="fa fa-list"></i><?php $categories = get_the_category();
$separator = ", ";
$output = '';
if($categories){
if($link_on_cat == "yes"){
foreach($categories as $category){
$output .= '' . $category->cat_name . '' . $separator;
}
} else {
foreach($categories as $category){
$output .= $category->cat_name . $separator;
}
}
echo trim($output, $separator);
} ?></span>
This is not working :
<span><i class="fa fa-list"></i><?php $categories = get_the_category();
$separator = ", ";
$output = '';
global $post, $post_id;
$post_type = $post->post_type;
$taxonomies = get_object_taxonomies($post_type);
if($categories){
if($link_on_cat == "yes"){
foreach($categories as $category){
$output .= '' . $category->cat_name . '' . $separator;
}
foreach ($taxonomies as $taxonomy) { $out .= "<li>".$taxonomy.": "; $terms = get_the_terms( $post->ID, $taxonomy );
if ( !empty( $terms ) ) {
foreach ( $terms as $term )
$out .= ''.$term->name.' ';
} }
} else {
foreach($categories as $category){
$output .= $category->cat_name . $separator;
}
}
echo trim($output, $separator);
} ?></span>
Of course I'm doing something wrong, but what ?
I have the below code to list the Array of terms, I am placing a comma between the terms if there are more than one term assigned to the post.
$terms = get_terms('my_term', $args);
if (!empty($terms) && !is_wp_error($terms)) {
$count = count($terms);
$i = 0;
$term_list = '<span>';
foreach ($terms as $term) {
$i++;
$term_list .= '#<span>' . $term->name . '</span>';
if ($count != $i) {
$term_list .= ', ';
} else {
$term_list .= '</span>';
}
}
}
Now, I would like place a & between the last two terms instead of a , if there are more than one term assigned to the post.
I think it is easier to solve it with an array.
$terms = get_terms('my_term', $args);
if (!empty($terms) && !is_wp_error($terms)) {
$term_array = [];
foreach ($terms as $term) {
$term_array[] = '#<span>' . $term->name . '</span>';
}
if(count($term_array) > 1){
$last = array_pop($term_array);
$term_list = '<span>' . implode(', ', $term_array) . '</span>';
$term_list .= ' & ' . $last;
} else {
$term_list = '<span>' . $term_array[0] . '</span>';
}
}
OR:
$terms = get_terms('my_term', $args);
if (!empty($terms) && !is_wp_error($terms)) {
$count = count($terms);
$i = 1;
$term_list = '<span>';
foreach ($terms as $term) {
$term_list .= '#<span>' . $term->name . '</span>';
if($i !== $count){
if($i === $count - 1){
$term_list .= ' & ';
} else {
$term_list .= ', ';
}
}
$i++;
}
$term_list .= '</span>';
}
Check if $count is equal to $i + 1:
if ($count != $i) {
if ($count == $i + 1)
$term_list .= '& ';
else
$term_list .= ', ';
} else {
$term_list .= '</span>';
}
That should do it.
You could check if the $count is equal to $i.
$i = 1;
if ($count != $i) {
$term_list .= ', ';
} else if ($count == $i) {
$term_list .= '& ';
} else {
$term_list .= '</span>';
}
Find the last element of the array, then just check each item within your loop against lastelement, then do your 'magic' ;).
Example:
$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
echo $v . '<br/>';
if($v == $lastElement) {
// 'Now you know that $v is the last element, do something';
}
}
I have 5 menu in the website which is coming dynamically :
menu1 menu2 menu3 menu4 menu5
Now I want to add menu6 before menu5 using php.
My code:
foreach ($collection as $category) {
$i++;
$menuCategory = $this->getCategoryAsArray($category, $currentCategory);
$class = '';
$class .= 'nav'. $i;
if($i == 1) {
$class .= ' first';
} elseif ($i == $count) {
$class .= ' last';
}
if($menuCategory['is_active']) {
$class .= ' active';
}
//if($this->hasChildProduct($category)) {
//$class .= ' parent';
//}
if($this->hasChildSubCategory($category)) {
$class .= ' parent';
}
$class .= ' level-top';
$html .= '<li class="level0 '. $class .'">';
$html .= '<a href="'. $menuCategory['url'] .'">';
$html .= '<span>'. $menuCategory['name'] .'</span>';
$html .= '</a>';
//if($this->hasChildProduct($category)) {
//$html .= $this->getChildProductMenuHtml($category, $i);
//}
if($this->hasChildSubCategory($category)) {
$html .= $this->getChildSubcategoryMenuHtml($category, $i);
}
$html .= '</li>';
}
Menu6 is the static link which code is:
<li class="vertical-submenu" id="static-menu"><a href="<?php echo $block->getUrl('menu6')?>"><?php echo __('menu6')?></li>
I am not getting the code because i am not aware of values coming in the array in foreach loop.
But I can explain the situation to you via Algorithm.
$i = 0;
foreach(expression){
if(value == "menu5"){
write("Menu 4")
}
Write("Menu ".$i)
$i++;
}
Hope your problem is resolved with this. If you need anything else or want to elaborate more about you problem text me at shahrukhusmaani#gmail.com
I have the below function which gets wordpress posts and outputs them in a bootstrap grid (3 posts per row). Each array chunk has 3 posts in it. Basically what I want to do is if the chunk is not complete and only has say 2 posts in it then the first post in that chunk gets "col-sm-offset-2" class added. I believe I need some way off counting the posts in the chunk but I'm not sure how to implement.
function post_events($atts) {
global $post;
$args = array(
'post_type' => 'event',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'ASC',
);
$posts = get_posts($args);
$posts_chunks = array_chunk($posts, 3);
$output = '';
foreach ($posts_chunks as $row) {
$output .= '<div class="row">';
foreach ($row as $post) {
setup_postdata($post);
$output .= '<div class="col-md-6 col-sm-6 event-item">';
$output .= '' .get_the_post_thumbnail(). '';
$output .= '<div class="event-item-text">';
$output .= '<h3>' .get_the_title(). '</h3>';
$output .= '<span class="event-date">' .get_the_date("d-m-Y"). '</span>';
$output .= '<p>' .wp_trim_words( get_the_content(), 40, '...' ). '</p>';
$output .= '</div>';
$output .= '</div>';
}
$output .= '</div>';
}
return $output;
}
add_shortcode('post_events','post_events');
You can just use count() on $row, and then set the class based on whether it's the first iteration or not:
$class = 'col-md-6 col-sm-6 event-item';
$count = count($row);
foreach( $row as $k => $post )
{
$cls = ($k == 0 && $count < 2) ? $class.' col-sm-offset-2' : $class;
setup_postdata($post);
$output.= '<div class="'.$cls.'">';
//...
}
Since you have chunked, the subarrays will be 0 based and the first post will be 0. So just check that and if the count is less than 3:
foreach ($posts_chunks as $row) {
$output .= '<div class="row">';
foreach ($row as $key => $post) {
$extra = ''; //set extra class to empty
if($key == 0 && count($row) < 3) { //check first post and count less than 3
$extra = 'col-sm-offset-2 '; //set extra class
}
setup_postdata($post);
//use $extra somewhere
$output .= '<div class="'.$extra.'col-md-6 col-sm-6 event-item">';
$output .= '' .get_the_post_thumbnail(). '';
$output .= '<div class="event-item-text">';
$output .= '<h3>' .get_the_title(). '</h3>';
$output .= '<span class="event-date">' .get_the_date("d-m-Y"). '</span>';
$output .= '<p>' .wp_trim_words( get_the_content(), 40, '...' ). '</p>';
$output .= '</div>';
$output .= '</div>';
}
$output .= '</div>';
}
The theme that I have been using for my wp site has related posts shortcode which works, but it doesn't hide the currently viewed post. I had some idea to add a variable before the query to a post so the query sees that post which is currently viewed has that variable set to true and skip it. Here is the code:
<?php
global $post;
$categories = get_the_category();
$ceker=false;
foreach ($categories as $category[0]) {
if ($ceker == false){
$ceker=true;
?>
content etc...
I use this in my own themes and it works. How can I do something similar to these shortcode that this theme uses:
#BLOG LIST...
if(!function_exists('dt_blog_posts')) {
function dt_blog_posts( $atts, $content = null ) {
extract(shortcode_atts(array(
'show_feature_image' => 'true',
'excerpt_length' => 35,
'show_meta' => 'true',
'limit' => -1,
'categories' => '',
'posts_column' => 'one-column', // one-column, one-half-column, one-third-column
), $atts));
global $post;
$meta_set = get_post_meta($post->ID, '_tpl_default_settings', true);
$page_layout = !empty($meta_set['layout']) ? $meta_set['layout'] : 'content-full-width';
$post_layout = $posts_column;
$article_class = "";
$feature_image = "";
$column = ""; $out = "";
//POST LAYOUT CHECK...
if($post_layout == "one-column") {
$article_class = "column dt-sc-one-column blog-fullwidth";
$feature_image = "blog-full";
}
elseif($post_layout == "one-half-column") {
$article_class = "column dt-sc-one-half";
$feature_image = "blog-twocolumn";
$column = 2;
}
elseif($post_layout == "one-third-column") {
$article_class = "column dt-sc-one-third";
$feature_image = "blog-threecolumn";
$column = 3;
}
//PAGE LAYOUT CHECK...
if($page_layout != "content-full-width") {
$article_class = $article_class." with-sidebar";
$feature_image = $feature_image."-sidebar";
}
//POST VALUES....
if($categories == "") $categories = 0;
//PERFORMING QUERY...
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }
$args = array('post_type' => 'post', 'paged' => $paged, 'posts_per_page' => $limit, 'cat' => $categories, 'ignore_sticky_posts' => 1);
$wp_query = new WP_Query($args);
$pholder = dt_theme_option('general', 'disable-placeholder-images');
if($wp_query->have_posts()): $i = 1;
while($wp_query->have_posts()): $wp_query->the_post();
$temp_class = $format = "";
if($i == 1) $temp_class = $article_class." first"; else $temp_class = $article_class;
if($i == $column) $i = 1; else $i = $i + 1;
$out .= '<div class="'.$temp_class.'"><!-- Post Starts -->';
$out .= '<article id="post-'.get_the_ID().'" class="'.implode(" ", get_post_class("blog-post", $post->ID)).'">';
if($show_meta != "false"):
$out .= '<div class="post-details"><!-- Post Details Starts -->';
$out .= '<div class="date"><span>'.get_the_date('d').'</span>'.get_the_date('M').'<br />'.get_the_date('Y').'</div>';
$out .= '<div class="post-comments">';
$commtext = "";
if((wp_count_comments($post->ID)->approved) == 0) $commtext = '0';
else $commtext = wp_count_comments($post->ID)->approved;
$out .= ''.$commtext.' <i class="fa fa-comment"></i>';
$out .= '</div>';
$format = get_post_format();
$out .= '<span class="post-icon-format"> </span>';
$out .= '</div><!-- Post Details ends -->';
endif;
$out .= '<div class="post-content"><!-- Post Content Starts -->';
$out .= '<div class="entry-thumb">';
if(is_sticky()):
$out .= '<div class="featured-post">'.__('Featured','iamd_text_domain').'</div>';
endif;
//POST FORMAT STARTS
if( $format === "image" || empty($format) ):
if( has_post_thumbnail() && $show_feature_image != 'false'):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail($post->ID, $feature_image, $attr);
$out .= '</a>';
elseif($pholder != "true" && $show_feature_image != 'false'):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$out .= '<img src="http://placehold.it/840x340&text='.get_the_title().'" alt="'.get_the_title().'" />';
$out .= '</a>';
endif;
elseif( $format === "gallery" ):
$post_meta = get_post_meta($post->ID ,'_dt_post_settings', true);
$post_meta = is_array($post_meta) ? $post_meta : array();
if( array_key_exists("items", $post_meta) ):
$out .= "<ul class='entry-gallery-post-slider'>";
foreach ( $post_meta['items'] as $item ) { $out .= "<li><img src='{$item}' alt='gal-img' /></li>"; }
$out .= "</ul>";
endif;
elseif( $format === "video" ):
$post_meta = get_post_meta($post->ID ,'_dt_post_settings', true);
$post_meta = is_array($post_meta) ? $post_meta : array();
if( array_key_exists('oembed-url', $post_meta) || array_key_exists('self-hosted-url', $post_meta) ):
if( array_key_exists('oembed-url', $post_meta) ):
$out .= "<div class='dt-video-wrap'>".wp_oembed_get($post_meta['oembed-url']).'</div>';
elseif( array_key_exists('self-hosted-url', $post_meta) ):
$out .= "<div class='dt-video-wrap'>".wp_video_shortcode( array('src' => $post_meta['self-hosted-url']) ).'</div>';
endif;
endif;
elseif( $format === "audio" ):
$post_meta = get_post_meta($post->ID ,'_dt_post_settings', true);
$post_meta = is_array($post_meta) ? $post_meta : array();
if( array_key_exists('oembed-url', $post_meta) || array_key_exists('self-hosted-url', $post_meta) ):
if( array_key_exists('oembed-url', $post_meta) ):
$out .= wp_oembed_get($post_meta['oembed-url']);
elseif( array_key_exists('self-hosted-url', $post_meta) ):
$out .= wp_audio_shortcode( array('src' => $post_meta['self-hosted-url']) );
endif;
endif;
else:
if( has_post_thumbnail() && $show_feature_image != 'false'):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail($post->ID, $feature_image, $attr);
$out .= '</a>';
elseif($pholder != "true" && $show_feature_image != 'false'):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$out .= '<img src="http://placehold.it/840x340&text='.get_the_title().'" alt="'.get_the_title().'" />';
$out .= '</a>';
endif;
endif;
//POST FORMAT ENDS
$out .= '</div>';
$out .= '<div class="entry-detail">';
$out .= '<h2>'.get_the_title().'</h2>';
if($excerpt_length != "" || $excerpt_length != 0) $out .= dt_theme_excerpt($excerpt_length);
$out .= '</div>';
if($show_meta != "true"):
$out .= '<div class="post-meta">';
$out .= '<div class="opsirnije">';
$out .= ''.'Opširnije »'.'';
$out .= '<ul>';
$out .= '<li><span class="fa fa-user"></span>'.get_the_author_meta('display_name').'</li>';
$categories = get_the_category();
$thiscats = "";
if($categories) {
foreach($categories as $category) {
$thiscats .= ''.$category->cat_name.', '; }
$thiscats = substr($thiscats,0, (strlen($thiscats)-2));
$out .= '<li><span class="fa fa-thumb-tack"></span>'.$thiscats.'</li>';
}
$out .= get_the_tag_list('<li><span class="fa fa-pencil"></span>', ', ', '</li>');
$out .= '</ul>';
$out .= '</div>';
endif;
$out .= '</div><!-- Post Content Ends -->';
$out .= '</article>';
$out .= '</div><!-- Post Ends -->';
endwhile;
if($wp_query->max_num_pages > 1):
$out .= '<div class="pagination-wrapper">';
if(function_exists("dt_theme_pagination")) $out .= dt_theme_pagination("", $wp_query->max_num_pages, $wp_query);
$out .= '</div>';
endif;
wp_reset_query($wp_query);
else:
$out .= '<h2>'.__('Nothing Found.', 'iamd_text_domain').'</h2>';
$out .= '<p>'.__('Apologies, but no results were found for the requested archive.', 'iamd_text_domain').'</p>';
endif;
return $out;
}
add_shortcode('dt_blog_posts', 'dt_blog_posts');
add_shortcode('dt_sc_blogposts', 'dt_blog_posts');
}
Answer was simple. Just added
'post__not_in' => array( get_the_ID() ))
in array.
Thx all...