wordpress have function the_category(''); for show all category assigned to te current post , but i need to get current category only child and not show parent .
for example my post have category category parent --> category child and the_category; print :your post cat is : ( category parent , category child )
i neeed parint , your post cat is : (category child) and not show parent .
Use get_the_category function , witch will return all categories asigned to a post ( this means all parents and childs allso ) so you can loop thru them and see witch one is parent and witch one is child and print the one you're trying to get . I suggest you build a function in you're theme functions file.
Update
For example let's say you whant to display the child category name in you're single.php theme file so you would do this:
<?php $child_category = post_child_category(get_the_ID()); ?>
<?php if ( $child_category ) echo $child_category->cat_name; ?>
In order for that to work you need to define post_child_category function in you're theme functions file ( if you look in you're theme directory you'll see a functions.php file , if not then you can create it now ) , so you would add the following :
if ( ! function_exists( 'post_child_category' ) )
{
function post_child_category( $id = null )
{
if ( $id = null )
return false;
$categories = get_the_category( $id );
if ( count($categories) > 0 )
{
return $categories[count($categories)-1];
} else {
return false;
}
}
}
Update
If you whant to display the category link you would do this :
<?php $child_category = post_child_category(get_the_ID()); ?>
<?php if ( $child_category ) : ?>
<a href="<?php echo get_category_link($child_category->cat_ID); ?>" title="<?php echo $child_category->cat_name;?>">
<?php echo $child_category->cat_name;?>
</a>
<?php endif;?>
<ul>
<?php
$blogCategoryID = "5"; // current category ID
$childCatID = $wpdb->get_col("SELECT term_id FROM $wpdb->term_taxonomy WHERE parent=$blogCategoryID");
if ($childCatID){
foreach ($childCatID as $kid)
{
$childCatName = $wpdb->get_row("SELECT name, term_id FROM $wpdb->terms WHERE term_id=$kid");
?>
<li><?php echo $childCatName->name; ?></li>
<?php
}
}
?>
</ul>
take a look at :
http://codex.wordpress.org/Function_Reference/wp_list_categories
this worked for me
$catID=$wp_query->query_vars['cat'];
$args = array('parent' => $catID);
$categories = get_categories( $args );
foreach($categories as $category) {
echo '<li><a href="' . get_category_link( $category->term_id ) . '" ' . '>' . $category->name.'</a> </li> ';
}
Related
I have a WordPress sidebar that I want to only display the children of the parent category. My structure is as follows
All Products > Parent Category > Children Categories
How do I get the sidebar to only display the Parent Category and Children Categories.
I read a solution to implement this code but I'm not sure where to put it inside the files.
<?php
if (is_category()) {
$cat = get_query_var('cat');
$this_category = get_category($cat);
$this_category = wp_list_categories('hide_empty=0&hierarchical=true&orderby=id&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");
if($this_category !='<li>No categories</li>')
{
echo '<h3>Products</h3>';
echo '<ul>'.$this_category.'</ul>';
}
}
?>
These are screenshots from what my shop looks like and what I want.
Create a shortcode in your theme's functions.php file as follows:
add_shortcode('child_category_list', 'get_child_category_list');
function get_child_category_list(){
ob_start();
// Only on product parent category pages
if( is_product_category() ) {
$parent = get_queried_object();
$categories = get_term_children( $parent->term_id, 'product_cat' );
if ( $categories && ! is_wp_error( $categories ) ) :
echo '<ul>';
echo '<li>';
echo ''.$parent->name.'';
echo '<ul>';
foreach($categories as $category) :
$term = get_term( $category, 'product_cat' );
echo '<li>';
echo '<a href="'.get_term_link($term).'" >';
echo $term->name;
echo '</a>';
echo '</li>';
endforeach;
echo '</ul>';
echo '<li>';
echo '</ul>';
endif;
}
return ob_get_clean();
}
Then, go to Appearance > Widgets, grab either shortcode or text widget into your sidebar and paste following shortecode:
[child_category_list]
Tested on localhost & its working fine.
I have a loop do display the different categories to go on the archive page.
How can y only display the categories one time ?
Currently, if two posts had the same category, there is two time the category
This is my code below
<div class="row ptb-20">
<?php
$args = array(
'category_name' => 'actualites',
);
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();?>
<div class="category-filter">
<div class="single-filter">
<?php
$categories = get_the_category();
$separator = ", ";
$output = ' ';
if ($categories) {
foreach ($categories as $category) {
$output .= '<li>' . $category->cat_name . '</li>';
}
echo trim($output, $separator);
}
?>
</div>
</div>
<?php
} // End while
} // End if
else { echo '<p>Aucune actualité trouvée</p>'; } ?>
<?php wp_reset_postdata(); ?>
</div>
Method 1: Exclude a Category from WordPress Using Plugin
First thing you need to do is to install and activate the Ultimate Category Excluder plugin. For more details, you should follow our guide on how to install a WordPress plugin.
Upon activation, you’ll need to go to Settings » Category Excluder page. It will display all the categories that are available on your WordPress blog.
Method 2: Exclude a Category from WordPress Homepage Using Code
This method requires you to add code to your WordPress files. If you haven’t done this before, then see our guide on how to copy and paste code snippets in WordPress.
You will need to add following code to your theme’s functions.php file or a site-specific plugin.
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-5' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );
Don’t forget to replace ID (-5) with your category ID. It will hide all blog posts from homepage belonging to the category that matches this ID.
Note: Make sure to add a minus (-) sign with the category ID.
Please refer: https://www.wpbeginner.com/wp-tutorials/how-to-exclude-a-category-from-your-wordpress-homepage/
If I understand your issue correctly, you can introduce a variable in which you would remember what categories has already been used, so you don't include them more than once.
<div class="row ptb-20">
<?php
$args = array(
'category_name' => 'actualites',
);
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();?>
<div class="category-filter">
<div class="single-filter">
<?php
$categories = get_the_category();
$categories_displayed = [];
$separator = ", ";
$output = ' ';
if ($categories) {
foreach ($categories as $category) {
if (!in_array($category->cat_name, $categories_displayed)) {
$output .= '<li>' . $category->cat_name . '</li>';
$categories_displayed[] = $category->cat_name;
}
}
echo trim($output, $separator);
}
?>
</div>
</div>
<?php
} // End while
} // End if
else { echo '<p>Aucune actualité trouvée</p>'; } ?>
<?php wp_reset_postdata(); ?>
</div>
I have a category "Decouverte" witch has three subcategories : "actualité", "vidéo" and "coup de coeur".
When I sort the posts according to their subcategories, everything works except for the category "video"; the category_slug displays "decouverte".
On my dashboard, I see this :
The subcategory "Video" is displayed last, maybe it's why it doesn't work ?
My code :
$categories = get_the_category();
$category_slug = $categories[0]->slug;
echo $category_slug;
if ( $category_slug == 'actualite' ) { ?>
<div class="picto_home icone_actualite"></div><?php
}
elseif ( $category_slug == 'video' ) { ?>
<div class="picto_home icone_video"></div><?php
}
elseif ( $category_slug == 'coupdecoeur' ) { ?>
<div class="picto_home icone_coupdecoeur"></div><?php
}
else { echo "Doesn't work"; } ?>
And the website : http://www.overso.me/ It's on the right block
Problem source
It's because you have got two categories applied to all posts.
Categories in each post are sotrted alphabetically.
In your case you take $category_slug = $categories[0]->slug;, which means:
Take first category slug name from categories array
For each post it is:
$categories[0] = Decouverte, $categories[1] = Video because D < V
$categories[0] = Actualite, $categories[1] = Decouverte because A < D
$categories[0] = Coup de coeur, $categories[1] = Decouverte because C < D
How to make it work as you want
Ok so here is my approach for your problem.
Before checking for $categories[0]->slug, lets check is $categories[0] object a PARENT category. You can do this by checking:
$categories = get_the_category();
// Remove parent category object from array if it's on first place
if($categories[0]->parent == 0){
unset($categories[0]);
$categories = array_values($categories);
}
As you see if $categories[0] is a parent category (if($categories[0]->parent == 0)), then remove this result from array $categories - unset($categories[0]).
Now you can just reset indexing of this array to starting from 0, by calling $categories = array_values($categories).
From now, you can easly call $categories[0]->slug, because there is no parent category on first place for sure.
Full code:
$categories = get_the_category();
// Remove parent category object from array if it's on first place
if($categories[0]->parent == 0){
unset($categories[0]);
$categories = array_values($categories);
}
$category_slug = $categories[0]->slug;
if ( $category_slug == 'child-1' ) {
echo "1111";
}
elseif ( $category_slug == 'child-2' ) {
echo "2222";
}
elseif ( $category_slug == 'child-3' ) {
echo "3333";
}
else { echo "Doesn't work"; }
Of course change if statements logic to your data.
More general solution for future reference
Ok, here is some general solution I wrote.
If you need to get only subcategories for any post, for any number of categories applied to the post, and no matter on which place parent category will be in the categories array, you should try this.
First, add this function to your functions.php file (or to your plugin file).
function du_get_post_subcategories( $post_id ){
$categories = get_the_category( $post_id );
$i = 0;
foreach ($categories as $category) {
if($category->parent == 0){
unset($categories[$i]);
}
$i++;
}
$categories = array_values($categories);
return $categories;
}
And then inside your loop you can call
$subcategories = du_get_post_subcategories( $post->ID );
If you have post ID, you can call this outside the loop as well
$subcategories = du_get_post_subcategories( $your_post_id );
This function will return all subcategories in the same format as get_the_category() function.
If you provide array with only one, parent category. Function will return an empty array.
Either this is harder than it needs to be or I am just not understanding WordPress/PHP very well :( All I want to do is show the child/sub categories of a specific parent category...but only if the post is in those subcategories. Specific example:
I am building a wine reviews website and these are the categories:
BrandSubcategory 1Subcategory 2etc.
RegionSubcategory 1Subcategory 2etc.
GrapeSubcategory 1Subcategory 2etc.
The parent categories will never change, and every post will have at least 1 subcategory selected under each parent, so in the LOOP I can just list the parents by name. But I am needing to dynamically output the subcategories, something like this:
Brand: <?php list_post_subcategories('brand'); ?>
Region: <?php list_post_subcategories('region'); ?>
Grape: <?php list_post_subcategories('grape'); ?>
Is there any easy way like this? It seems like this should be a basic function in Wordpress? I've looked at the functions 'get_categories' and 'in_category' but they don't seem to be able to do this.
<?php $post_child_cat = array();
foreach((get_the_category()) as $cats) {
$args = array( 'child_of' => $cats->cat_ID );
$categories = get_categories( $args );
if( $categories ) foreach( $categories as $category ) {
echo $category->cat_name; }
} ?>
try this
I posted to Wordpress Answers to get more help and #Milo gave a great code solution:
// get top level terms
$parents = get_terms( 'category', array( 'parent' => 0 ) );
// get post categories
$categories = get_the_terms( $post->ID, 'category' );
// output top level cats and their children
foreach( $parents as $parent ):
// output parent name and link
echo '' . $parent->name . ': ';
// initialize array to hold child links
$links = array();
foreach( $categories as $category ):
if( $parent->term_id == $category->parent ):
// put link in array
$links[] = '' . $category->name . '';
endif;
endforeach;
// join and output links with separator
echo join( ', ', $links );
endforeach;
You can use array_map so you can return only the categories that you want. For example:
array_map( function( $cat ) {
if ( $cat->parent != 0 ) {
return $cat;
}
},
get_the_category()
);
I want to ask on how to get the link of each category that have related post on it. I only got some code that will only display parent category. Any help would be much appreciated. Thanks!
<?php
$categories = get_categories();
foreach ($categories as $cat){
if($cat->parent < 1){
echo $cat->cat_name ;
}
}
?>
Sounds like you may want get_category_link - something like:
$categories = get_categories();
foreach ($categories as $cat) {
$category_link = get_category_link($cat->cat_ID);
echo '' . esc_html($cat->name) . '';
}
should print out the links to the categories for you.
According to Function Reference/get category link
<?php get_category_link( $category_id ); ?>
Example:
<?php
// Get the ID of a given category
$category_id = get_cat_ID( 'Category Name' );
// Get the URL of this category
$category_link = get_category_link( $category_id );
?>
<!-- Print a link to this category -->
Category Name