How to display only certain categories in Wordpress - php

I'm working in Wordpress and implemented some PHP to display all categories on a page (by a shortcode). By clicking on a category it links to a new page displaying all posts of that very category.
How do I display only certain categories, for instance by id and/or name of the cateogry?
One post has two categories (a : A & B or A & C). So one post a always has one category A, and one category B or C.
Here's my code:
function swerft_categories( ){
ob_start();
$categories = get_categories();
echo '<div class="swerft_cat">';
foreach($categories as $category) {
echo '<div class="swerft_cat_single col-lg-3 col-md-3 col-sm-6 col-xs-12">';
echo '<div class="swerft_cat_single_inner">';
$thim_group_custom_title_bg_img = get_term_meta( $category->term_id, 'thim_group_custom_title_bg_img', true );
if ($thim_group_custom_title_bg_img) {
$image_id = $thim_group_custom_title_bg_img['id'];
if ($image_id) {
$post_thumbnail_img = wp_get_attachment_image_src( $image_id, 'full' );
echo '<img src="' . $post_thumbnail_img[0] . '" alt="' . $category->name . '" />';
}
}
echo '<h5>'. $category->name .'</h5>';
echo '<p>'. $category->description . $category->count . '<span> Seminare </span>' . '</p>';
echo '</div>';
echo '</div>';
}
echo '</div>';
return ob_get_clean();
}
add_shortcode( 'swerft_categories', 'swerft_categories' );
I tried this in the first few lines for example with no success:
function swerft_categories($args){
ob_start();
$args = array('hide_empty'=> 1,
'name' => 'B');
$categories = get_categories($args);
1) I want only one certain relation to be displayed. Let's say: only the relation of a : A & B
2) I want the count to only show the amount of posts based on the relation above.
3) By clicking on a category based on this relation, I want only those posts to be displayed of course.

I was able to find a solution for the above mentioned problem together with a colleague. See the code below, I hope it may help someone maybe; and thanks for anyone considering this task though ;)
// Function to only show individual seminars after click on category on category-page
function swerft_filter_posts_open_individual_seminare( $query ) {
$offene_seminare = isset($_GET['offene_seminare']) ? boolval($_GET['offene_seminare']) : false;
$individual_seminars_category_id = 91;
if($query->is_category() && $query->is_main_query()) {
if ($offene_seminare) {
$query->set( 'category__not_in', $individual_seminars_category_id );
} else {
$query->set( 'category__in', $individual_seminars_category_id );
}
}
}
add_action( 'pre_get_posts', 'swerft_filter_posts_open_individual_seminare' );
// Function to only count individual seminars in overview
function swerft_count_individual_seminars_in_category($category_id) {
$individual_seminars_category_id = 91;
$query_args = array(
'post_type' => 'post',
'category__and' => array($individual_seminars_category_id, $category_id)
);
$query = new WP_Query( $query_args );
$count = $query->found_posts;
return $count;
}

Related

Display a ACF Category Taxonomy Field With a List of all Categories

I added a Text field to the Category taxonomy using ACF so that I can add a font awesome icon code to be displayed in a list of all categories.
The end result I am looking for is a list of all categories names linked to their respective category pages (if they have posts or not) with the icon from the custom field before each category name.
Reviewing the ACF documents and looking around for a solution I have only been able to display one icon at a time or just create errors.
Is there a more straight forward way I can loop through all of the categories and include the name, link and icon from my ACF custom field in the way I would do so for posts that have a custom field added on to it?
Here is the code I have so far but it only shows one at a time even though I am trying to use a foreach to loop through them all:
<?php
$categories = get_the_category();
$separator = ' ';
$output = '';
foreach( $categories as $category ) {
$terms = get_the_terms( get_the_ID(), 'category');
if($terms) {
$term = array_pop($terms);
$icon = get_field('cat_icon', $term );
}
echo $icon;
$output .= '' . esc_html( $category->name ) . '' . $separator;
}
echo trim( $output, $separator ); ?>
Any help is appreciated, thank you!
As requested here is a screenshot, you can see it is displaying the icon from my custom field but only one category out of the 3 I currently have added.
You can use get_terms. try the below code.
<?php
$categories = get_terms( array(
'taxonomy' => 'category',
'hide_empty' => false
) );
$separator = ' ';
$output = '';
foreach( $categories as $category ) {
if($category) {
$icon = get_field('cat_icon', $category );
}
echo $icon;
$output .= '' . esc_html( $category->name ) . '' . $separator;
}
echo trim( $output, $separator );
?>

Order by 'rand' not working on Wordpress foreach loop

I am trying to order some data by 'rand' on a foreach loop I have created which is outputting some users which I have created a custom role for. all the other bits are great apart from this.
This is the current state of the loop:
<?php
// Featured Consultants
$consultants = get_users( 'role=consultant&number=2' );
// Array of WP_User objects.
foreach ( $consultants as $consultant ) {
// Check for 'featured' Consultants
if($consultant->featured == 'Yes'){
echo '<div class="columns six consultantCard">';
echo '<div class="columns four">';
echo get_avatar( $consultant->id, 150 );
echo '</div>';
echo '<div class="columns eight">';
// Get users details
echo '<span class="name">' . esc_html( $consultant->first_name ) . ' ' . esc_html( $consultant->last_name ) . '</span>';
echo '<span class="jobTitle">' . esc_html( $consultant->job_title ) . '</span>';
echo '<span class="location">Currently based in ' . esc_html( $consultant->current_location ) . '</span>';
// Check if user is less than 30 days old
if( strtotime($consultant->user_registered) < strtotime('30 days') ){
echo '<span class="newTag">New</span>';
}
// Check if user is featured
if($consultant->featured == 'Yes'){
echo '<span class="featuredTag">Featured Candiate</span>';
}
// Check if user is accredited
if($consultant->accredited == 'Yes'){ ?>
<span class="icon"><img src="<?php bloginfo('template_url');?>/assets/img/icons/accreditedIcon.png" /></span>
<?php echo '<span class="accreditedTag">Bench Accredited</span>';
}
echo '</div>';
echo '</div>';
} else{
echo 'No Featured Consultants';
}
}
?>
It just appears to be showing the latest entries and nothing more. I tried to also create an array but still the same result like so:
$consultant = array(
'role' => 'consultant',
'order' => 'rand'
);
We can use the get_users() to get a list of authors, users with a specific role, a user with specific meta, etc. The function returns users which can be ordered by ID, login, nickname, email, URL, registered, display_name, post_count, or meta_value. But there is no random option such as what get_posts() function provides to shows posts randomly.
Since the get_users() function uses WP_User_Query class, there is an action hook pre_user_query we can use to modify the class variable. The idea is using our own 'rand' order by the parameter. If we put 'rand' to the orderby parameter, user_login will be used instead. In this case, we need to replace it with RAND() to result in users randomly. In this example below, we I ‘rand’ and you can use your own order by name.
// Add this code in your function.php
add_action( 'pre_user_query', 'my_random_user_query' );
function my_random_user_query( $class ) {
if( 'rand' == $class->query_vars['orderby'] )
$class->query_orderby = str_replace( 'user_login', 'RAND()', $class->query_orderby );
return $class;
}
The WP_User_Query contains order by query and the our arguments. Now, we have a new order by parameter to WordPress.
$users = get_users( array(
'orderby' => 'rand',
'number' => 5
));
print_r( $users );

array to exclude specific categories from showing as FIRST category using get_the_category()

I'm using this code to show only the first category of a post on my page template but I need to find a way to exclude some specific categories from it
$category = get_the_category(); echo $category[0]->cat_name;?
Example:
Let's say that I have a post on tree categories: "admin cat" and "admin cat2" and "item cat". If I use this function, the output will be:
This post is under "admin cat"!
and I need it to be:
This post is under "item cat"!
Is it possible to add an array of cats that will be omitted on the output to my code or should I be using other method?
Try this one: https://wordpress.org/support/topic/exclude-categories-from-the_category/
<?php the_excluded_category(array(1,328,338,339)); ?>
function the_excluded_category($excludedcats = array()){
$count = 0;
$categories = get_the_category();
foreach($categories as $category) {
$count++;
if ( !in_array($category->cat_ID, $excludedcats) ) {
echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "Cortos de %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>';
if( $count != count($categories) ){
echo ", ";
}
}
}
}
Simply loop through your category array and match each item against an array of excluded categories. This will return the first non-matching category.
function getCategory() {
$categories = array('admin cat','admin cat2', 'item cat', 'some other cat', 'dog');
$excluded_categories = array('admin cat','admin cat2');
foreach($categories as $category) {
if (!in_array($category,$excluded_categories)) {
return $category;
}
}
return false;
}
echo getCategory();
// outputs 'item cat'
?>

Wordpress shortcode shows as plain text in one view, works in other

I have this complex loop:
<?php
$args = array(
'cat' => 54,
'order' => 'ASC',
'posts_per_page' => -1
);
$query = new WP_Query($args);
$q = array();
while ( $query->have_posts() ) {
$query->the_post();
$a = '<h2>' . get_the_title() .'</h2>'
. get_the_post_thumbnail() .
'<p>' . get_the_content("...plačiau") . '</p>';
$categories = get_the_category();
foreach ( $categories as $key=>$category ) {
$b = '<h1 class="thetitle">' . $category->name . '<span>Išskleisti <i class="fa fa-arrow-circle-down"></i></span></h1>';
}
$q[$b][] = $a; // Create an array with the category names and post titles
}
/* Restore original Post Data */
wp_reset_postdata();
foreach ($q as $key=>$values) {
echo $key;
echo '<div class="straipsniai">';
foreach ($values as $value){
if (count($values) == 1) {
echo '<div class="vienas">' . $value . '</div>';
} else if (count($values) == 2) {
echo '<div class="du">' . $value . '</div>';
} else if (count($values) == 3) {
echo '<div class="trys">' . $value . '</div>';
} else {
echo '<div>' . $value . '</div>';
}
}
echo '</div>';
}
?>
Which worked for me, gave me this nice list/accordion:
http://bruzienesklinika.lt/web/gydytojai/
Now, each person in the category has some articles as posts and I want a list of their articles under their description. (basic Title + exerpt + read more link)
I've tried to do this by using "List category posts" plugin which allows me to use [catlist id=24] shortcode, but the problem is that browser prints it as plain text, source shows [catlist id=24](You can open the most bottom "GYDYTOJA REUMATOLOGĖ" tab to see that). The shortcode does work inside page, which is rendered by single.php, but it does not show when rendered in the loop I gave you in the beginning of the question.
SO, the question is, how do I make the shortcode work in the initial list, where all the categories are listed with posts inside the accordion.
Now it is not the problem of this certain plugin because no shortcodes work in that accordion list.
Or maybe you have an idea how to do this the other way?

wordpress - display subcategory siblings when viewing a single post

Thank you all for a great site. I'm learning a lot. I'm trying to get my subcategory siblings to show when a single post is clicked on. I have set up my parent categories using the wordpress menu. I am using a php widget to call for the children (subcategories) in a separate menu (and then style with CSS). The code I'm using is showing the specific (relevant) children when each category is clicked on; however I am unable to figure out how to make them appear when viewing a post.
<?php
if(is_category()) {
$breakpoint = 0;
$thiscat = get_term( get_query_var('cat') , 'category' );
$subcategories = get_terms( 'category' , 'parent='.get_query_var('cat') );
if(empty($subcategories) && $thiscat->parent != 0) {
$subcategories = get_terms( 'category' , 'parent='.$thiscat->parent.'' );
}
$items='';
if(!empty($subcategories)) {
foreach($subcategories as $subcat) {
if($thiscat->term_id == $subcat->term_id) $current = ' current-cat'; else $current = '';
$items .= '
<li class="cat-item cat-item-'.$subcat->term_id.$current.'">
'.$subcat->name.'
</li>';
}
echo "<ul>$items</ul>";
}
unset($subcategories,$subcat,$thiscat,$items);
}
?>
I'm attempting to mimic the behavior of this menu at pioneer woman.com
Any help or a better solution would greatly be appreciated.
Thanks,
This lists all child categories of the current post's category:
<?php
echo '<ul>';
$post_child_cat = array();
foreach((get_the_category()) as $cat) {
$args = array( 'child_of' => $cat->cat_ID );
$categories = get_categories( $args );
if( $categories ) foreach( $categories as $category ) {
echo '<li class="cat-item cat-item-'.$category->term_id.'">'.
'<a title="'.$category->description.'" href="';
echo bloginfo('url');
echo '/category/'.$cat->slug.'/'.$category->slug.'">'.
$category->name.'</a></li>';
}
}
echo '</ul>';
?>

Categories