Wordpress - Get the taxonomy of a post hierarchically - hierarchy

I would like to get all the taxonomy of one post (in a loop), hierarchically. Example I have those taxonomies, and the ID of the tax in bracket.
Tax1(1)
-Tax2(3)
--Tax3(2)
I would like to gather them, in an array maybe, in this order. Right now I manage to get an array of those 3, but the order is wrong. I can't order it by id, since the ID are not ordered at first. I can't also order it by name and slug. (Names of my current taxonomies are not Tax1, Tax2...)
The code I have at the moment is
$args = array('orderby' => 'term_order', 'order' => 'ASC', 'fields' => 'all');
$productcategories = wp_get_object_terms($post->ID, 'guide_type', $args);

Use "Wordpress" Walker class to create a hierarchy of the taxonomy
<?php
class Walker_Quickstart extends Walker {
// Tell Walker where to inherit it's parent and id values
var $db_fields = array(
'parent' => 'parent',
'id' => 'term_id'
);
/**
* At the start of each element, output a <p> tag structure.
*/
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$output .= sprintf( "\n<p>%s %s (%s)</p>\n",
str_repeat('&dash;', $depth),
$item->name,
$item->term_id
);
}
}?>
This class will create a hierarchy of elements. Use this class with your returned elements like this :
$args = array('orderby' => 'term_order', 'order' => 'ASC', 'fields' => 'all');
$productcategories = wp_get_object_terms($post->ID, 'guide_type', $args);
$walk = new Walker_Quickstart();
echo $walk->walk($productcategories, 0);

Was about to get something with this function that I made, But Vikash Kumar gave me a better answer, thanks !
function get_term_top_most_parent($post_id, $taxonomy){
$return = array();
$registeredcat = 0;
$newparent = '';
$catcount = 0;
$firstlevels = wp_get_object_terms( $post_id, $taxonomy); //post id, taxo, args
foreach ($firstlevels as $key => $value){
if($value->parent == 0 ){
//$firstlevel = $value->term_id; //23
$newparent = $value->term_id;
array_push($return, $value);
$registeredcat += 1;
}
$catcount += 1;
}
return $return;
}

Related

Show all terms excluding the current page

The following lists all of the terms, can I get help revising it so that it shows all terms except the the active/current page? Thank you.
$terms = get_terms( 'topics', array(
'orderby' => 'name',
'order' => 'ASC',
));
if ( ! empty( $terms ) ){
foreach ( $terms as $term ) {
$term_thumb = get_field('image', $term);
echo '<li><img src="' .$term_thumb['url']. '"><span class="model">'.$term->name .'</span></li>';
}
}
You can do something like this:
// create an empty array holder
$current_tax_ids = array();
// get the post terms
$current_tax = get_the_terms( $post->ID, 'topics' );
// creating loop to insert ids
foreach( $current_tax as $tax ) {
$current_tax_ids[] = $tax->term_id;
}
$args = array(
'taxonomy' => 'topics',
'hide_empty' => 0,
'exclude' => $current_tax_ids // exclude the terms
);
// get all the terms
$all_terms = get_terms($args);
// now do whatever you want
so if you follow my comments it should be clear, but basically you want to get the current post terms and store the id in an array, then simply exclude the ids when you do get_terms .

Get no of posts inside with a term for a custom taxonomy

How can i get the no of posts inside a term of a custom taxonomy ? (including the posts that are attached to a child term).
For example i have:
term (2 posts)
-child term (2 posts)
--child child term (1 post)
Right now i'm, doing it like this:
$categories = get_terms($taxonomy,$args);
foreach ($categories as $categ) {
print $categ->name.' / '.$categ->count;
}
But for "term" i get only 2 posts when i really need to show 5( 2 from "term" and 3 from it's children).
Thanks
There is an easier way to do this: do a standard WP_Query with taxonomy parameters:
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'your_custom_taxonomy',
'field' => 'slug',
'terms' => 'your-parent-term-name',
),
),
);
$query = new WP_Query( $args );
// Get the count
$count = $query->post_count;
If you don't know the name(s) of terms within a taxonomy, you can do a query and pass their IDs as an array to WP_Query. See this post on WPSE for more info.
This is something I run into few times, and I changed the code from PatchRanger on bountify to make it work with taxonomies (so please note this solution is based on his work):
function wp_get_term_postcount($term) {
$count = (int) $term->count;
$tax_terms = get_terms($term->taxonomy, array('child_of' => $term->term_id));
foreach ($tax_terms as $tax_term) {
$count += wp_get_term_postcount_recursive($tax_term->term_id);
}
return $count;
}
function wp_get_term_postcount_recursive($term_id, $excludes = array()) {
$count = 0;
foreach ($tax_terms as $tax_term) {
$tax_term_terms = get_terms($tax_term->name, array(
'child_of' => $tax_term->term_id,
'exclude' => $excludes,
));
$count += $tax_term->count;
$excludes[] = $tax_term->term_id;
$count += wp_get_term_postcount_recursive($tax_term->term_id, $excludes);
}
return $count;
}
The recursive function is there to prevent double counting of childs. You can add those two functions inside functions.php.
Then update your code to use it:
$categories = get_terms($taxonomy, $args);
foreach($categories as $categ) {
print $categ->name.' / 'wp_get_term_postcount($categ);
}

Hide specific category in listings

I'm working on a Wordpress theme. The theme is Classifieds theme from premiumpress. The theme has a shortcode to list all the listings. The corresponding shortcode is [LISTINGS].
The function for the shortcode is as follows
/* =============================================================================
[LISTINGS] - SHORTCODE
========================================================================== */
function wlt_page_listings( $atts, $content = null ) {
global $userdata, $wpdb, $CORE; $STRING = ""; $extra=""; $i=1; $stopcount = 4;
extract( shortcode_atts( array( 'query' => '', 'show' => '', 'type' => '', 'cat' => '', 'orderby' => '', 'order' => '', 'grid' => "no", 'featuredonly' => "no"), $atts ) );
// SETUP DEFAULTS
if(!isset($atts['show']) || (isset($atts['show']) && $atts['show'] == "") ){ $atts['show'] = 5; }
if($atts['type'] == ""){ $atts['type'] = THEME_TAXONOMY.'_type'; }
if($atts['orderby'] == ""){ $atts['orderby'] = "post_title"; }
if($atts['order'] == ""){ $atts['order'] = "desc"; }
// DEFAULT FOR LIST STYLE
if($grid == "yes"){
$sstyle = "grid_style";
$STRING .= '<script language="javascript">jQuery(window).load(function() { equalheight(\'.grid_style .item .thumbnail\');});</script>';
}else{
$sstyle = "list_style";
}
$query= str_replace("#038;","&",$query);
if(strlen($query) > 1){
// ADD ON POST TYPE FOR THOSE WHO FORGET
if(strpos($query,'post_type') == false){
$args = $query ."&post_type=".THEME_TAXONOMY."_type";
}else{
$args = $query;
}
}elseif($featuredonly == "yes"){
$args = array('posts_per_page' => $atts['show'],
'post_type' => $atts['type'], 'orderby' => $atts['orderby'], 'order' => $atts['order'],
'meta_query' => array (
array (
'key' => 'featured',
'value' => 'yes',
)
)
);
}else{
/*** default string ***/
$args = array('posts_per_page' => $atts['show'], 'post_type' => $atts['type'], 'orderby' => $atts['orderby'], 'order' => $atts['order'] );
}
/*** custom category ***/
if(strlen($atts['cat']) > 1){
$args = array('tax_query' => array( array( 'taxonomy' => str_replace("_type","",$atts['type']) ,'field' => 'term_id','terms' => array( $atts['cat'] ))), 'posts_per_page' => $atts['show'] );
}
// BUILD QUERY
$the_query = new WP_Query( hook_custom_queries($args) );
if ( $the_query->have_posts() ) {
$STRING .= '<div class="_searchresultsdata"><div class="wlt_search_results row '.$sstyle.'">';
while ( $the_query->have_posts() ) { $the_query->the_post(); $post = get_post();
$STRING .= '<div class="item '.hook_gallerypage_item_class('col-md-4').$CORE->FEATURED($post->ID).'">'.hook_item_cleanup(hook_gallerypage_item($CORE->ITEM_CONTENT($post))).'</div>';
}
$STRING .= '</div></div><div class="clearfix"></div>';
}
// END QUERY
wp_reset_postdata();
return $STRING;
}
add_shortcode( 'LISTINGS', array($this,'wlt_page_listings') );
The shortcode does not have an attribute to hide certain categories. I need to display all listings, except the ones in wedding category, which is a custom taxonomy. Is there any way to do that with the above code?
Will something like this work?
if ( is_tax( 'listing', 'wedding' ) ) {
do not display the wedding listings and display the rest}
Any suggestions?
EDITS:
This my online site url : http://webzer.comxa.com/
The main page shows the all the products.I like to have all but not one that is from wedding category coz i have separate page to list wedding category.
i have tried this where 51 is the page id of my home store page
if ( is_page( 51 ) && is_tax( 'listing', 'wedding' ) ) {
?><style>.caption {display:none!important;}</style>
<?php } ?>
this also didn't work
Consider this :
change
function wlt_page_listings( $atts, $content = null ) {
to
function wlt_page_listings( $atts, $content = null, $exclude=array(99) ) { // 99 is wedding cat id
where $exclude is an optional array of excluded cat names (99 in there for ease of testing/use)
Then in the
while ( $the_query->have_posts() ) {
add something like this:
$post = get_post(); // get post obj, will use the ID attr
$cats = wp_get_post_categories( $post->ID )); // returns array of IDs for all cats
foreach($exclude as $x){ // loop on the excluded cat ids
if(in_array($x, $cats))continue; // if excluded skip
}
http://codex.wordpress.org/Function_Reference/wp_get_post_categories
I think this will work or at least got you close.
display:none is bad mojo as the content will still be in your source code for others to see.
I hope I addressed the problem correctly for you, cheers.

Gettin atrribute thumbnail from node from a wordpress rss feed

I've been trying to get this seemingly easy peace of code to work.
I'm loading rss from a wordpress site and it all works fine except for the thumbnails. Since in the XML they are set as an attribute instead of a nodeValue i can't seem to get import them. (i've really tried a lot)
$rss = new DOMDocument();
$rss->load('http://goalprogramme.wordpress.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
// in XML it looks like <media:thumbnail url="http://goalprogramme.files.wordpress.com/2014/01/dsc_0227.jpg?w=150"/>
//echo $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url');
//push items
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
'thumbnail' => $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url') // this line doesn't work !!!
);
array_push($feed, $item);
}
Any help would be greatly appreciated.
Thanks so much in advance!
Hours later i've created another piece of code that does work. If anyone needs it it, here it is:
$feed_array = array();
$feed = simplexml_load_file('http://goalprogramme.wordpress.com/feed/');
foreach ($feed->channel->item as $item) {
$title = (string) $item->title;
$description = (string) $item->description;
$link = (string) $item->link;
$date = (string) $item->date;
if ($media = $item->children('media', TRUE)) {
if ($media->thumbnail) {
$attributes = $media->thumbnail->attributes();
$thumbnail = (string)$attributes['url'];
}
}
$item = array (
'title' => $title ,
'desc' => $description,
'link' => $link,
'date' => $date,
'thumbnail' => $thumbnail
);
array_push($feed_array, $item);
}

List authors that have written certain number of posts in category/tags in Wordpress

I'm struggling to get the list of authors on the category page. I need to list the authors who have written at least 5 articles in that category.
I need something like this in tags also.
Any idea how to do this in wordpress?
Its only possible with a custom SQL query so here is a simple function which should return an array with user id's of users with at least $n posts in the current term archive, which means it should work in categories, tags and custom taxonomies
function get_authors_with($num = 5){
global $wpdb;
$term_slug = get_query_var( 'term' );
$taxonomyName = get_query_var( 'taxonomy' );
$current_term = get_term_by( 'slug', $term_slug, $taxonomyName );
$sub_q = $wpdb->prepare("SELECT * FROM $wpdb->posts
INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE ($wpdb->term_taxonomy.term_id = %s
AND $wpdb->term_taxonomy.taxonomy = '%s'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_status = 'publish')",
$current_term->term_id,
$taxonomyName
);
$sql = $wpdb->prepare("SELECT $wpdb->posts.post_author, FROM (%s)
GROUP BY $wpdb->posts.post_author
HAVING count(*) > %s",
$sub_q,
$num
);
return $wpdb->get_results($sql);
}
Try this.
function list_author_in_this_cat ($with) {
if (is_category()) {
$current_category = get_query_var('cat');
$args = array(
'numberposts' => -1,
'category' => $current_category,
'orderby' => 'author',
'order' => 'ASC'
);
} else {
$tag_id = get_query_var('tag_id');
$args = array(
'numberposts' => -1,
'tag__in' => $tag_id,
'orderby' => 'author',
'order' => 'ASC'
);
}
$cat_posts = get_posts($args);
$author_id_array = array();
$user_posts = array();
foreach( $cat_posts as $cat_post ):
$user_posts[$cat_post->post_author][] = $cat_post->ID;
endforeach;
foreach( $user_posts as $key => $user_post ):
$user_post = array_unique($user_post);
$count_user_posts[$key] = count($user_post);
if ($count_user_posts[$key] >= $with) {
$author_id_array[] = $key;
}
endforeach;
return $author_id_array; }
In your theme files, place this code wherever you want the list of authors to be displayed:
if (is_category() || is_tag()) {
$at_least = 5; // at least 5 articles in current category or tags
$author_array = list_author_in_this_cat ($at_least);
foreach (array_slice($author_array, 0, 4) as $author) : // limit 4 results
$name = get_userdata($author)->display_name;
$link = get_userdata($author)->user_login;
echo "<a href='/author/".$link."'>".$name."</a>\n";
endforeach;
}
Add the following code to your theme's function.php
function get_authors_in_category ( $category_id, $min_posts ) {
$posts = get_posts( array( 'numberposts' => 1000, 'category' => $category_id ) );
$author_count = array();
foreach ($posts as $post) {
if( array_key_exists( get_the_author_meta( 'display_name', $post->post_author ), $author_count ) ) {
$author_count[get_the_author_meta( 'display_name', $post->post_author )]++;
} else { $author_count[get_the_author_meta( 'display_name', $post->post_author )] = 1; }
}
$authors = array();
foreach ( $author_count as $author_name => $count ) {
if ( $min_posts <= $count ) {
$authors[] = $author_name;
}
return $authors;
}
This function as you can see returns an array of authors who have a minimum number of posts in a category. Category ID has to be passed, this can be obtained using the wordpress function get_cat_ID.
You can call this function from any where in the theme and display the authors as you wish.
Note: This is a more resource intensive than the custom SQL functions. Also this function might have some errors, I typed it here and didn't test it.
I did some simple coding with query post method.,
<?php
$cur_cat_id = get_cat_id(single_cat_title("",false));
$posts=query_posts("cat=$cur_cat_id&order=ASC");
foreach($posts as $post){
$number_of_posts = number_format_i18n(get_the_author_posts($post->post_author));
if($number_of_posts>5)
{
echo the_author_meta('user_nicename',$post->post_author)."(".number_format_i18n(get_the_author_posts($post->post_author)).")<br>";
}
}
?>
I think this may help you to resolve your problem.

Resources