This WordPress function will retrieve category object by category slug. All category information is available in the category object. WordPress | get_category_by_slug() Function.
Below is the syntax of get_category_by_slug() Function, how to use in your WordPress plugin or theme file.
Syntax:
1 | <?php get_category_by_slug( $slug ); ?> |
Used Parameters:
$slug
: (string) (required) The category slug.
Below is an example of get_category_by_slug() function.
Example 1:
1 2 3 4 | <?php $idObj = get_category_by_slug('category-slug'); $id = $idObj->term_id; ?> |
Example 2:
Below fucntion will return all the children categories.
1 2 3 4 5 6 7 8 | function get_children_categories($parent_slug) { $c = get_category_by_slug($parent_slug); if ($c) { $category_id = $c->term_id; return get_categories(array('child_of' => $category_id)); } } |
Example 3:
Here is another example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | function loop_category($category) { $idObj = get_category_by_slug($category); $cat_name = $idObj->name; if ($category === 'news') { $number = 4; } else { $number = 1; } $args = array('posts_per_page' => $number, 'category_name' => $category); $posts_array = get_posts($args); $length = count($posts_array); if ($length > 0) { echo '<a href="' . get_category_link($idObj->cat_ID) . ' " ><h3 class="big-article-title">' . $cat_name . '</h3></a>'; global $post; foreach ($posts_array as $key => $post) { setup_postdata($post); if ($key === 0) { get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format()); } else { if ($key === 1) { echo '<ul class="other-post-list length' . ($length - 1) . '">'; } get_template_part('templates/content', 'post-intro'); if ($key === $length) { echo '</ul>'; } } } wp_reset_postdata(); } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.