Check category in wp loop - wordpress

I have a wp query loop. I want to check if the post belongs to some categories. I can get the category using the_category(). I have tried
if(the_category()==`car`){do somthing}
and how to push all the remaining posts except the car category after to all the 'car' category.

the_category() returns many categories.
You might want to try get the category
$categories = get_the_category();
foreach($categories as $cat) {
if($cat->cat_name == 'car') {
// do something
}
}

You can run two queries here. The first query gets all posts from the car caregory. The second query gets all other posts except posts from the car category. Just remember to change CATID FOR CAR with the id of the car category, and don't forget the minus sign before the ID in the second query. The minus sign means exclude.
You can read more on this in the codex: WP_Query
$do_not_duplicate = array();
$args = array(
'cat' => CATID FOR CAR
);
$carargs = new WP_Query( $args );
if( $carargs->have_posts()):
while ($carargs->have_posts()) : $carargs- >the_post();
$do_not_duplicate[] = $post->ID;
<----your loop---->
endwhile;
endif;
wp_reset_postdata();
$args2 = array(
'cat' => -CATID FOR CAR,
'post__not_in' => $do_not_duplicate
);
$restargs = new WP_Query( $args2 );
if( $restargs->have_posts()):
while ($restargs->have_posts()) : $restargs- >the_post();
$do_not_duplicate[] = $post->ID;
<----your loop---->
endwhile;
endif;
wp_reset_postdata();

Related

How to customize/change the loop query

We have a page that is divided into two columns. Each column has a loop that fills the column with Posts from different categories.
What we want:
Column A - Shows posts with category X and Y
Column B – Shows posts with category X (Except posts that also have category Y)
The problem:
We’re not able to exclude from Column B the posts that are from category X but also Y – The idea is to show in column B post only with category X
From what we have researched we assume that we will have to customize the loop in column B but we don't know how to access it.
What are we missing here?
It's fairly easy to understand. When you define a new custom query (a custom loop), you're referencing a multitude of arguments against it.
In your case we are interested by the categories parameters.
Category Parameters
Show posts associated with certain categories.
cat (int) – use category id.
category_name (string) – use category slug.
category__and (array) – use category id.
category__in (array) – use category id.
category__not_in (array) – use category id.
Source # https://developer.wordpress.org/reference/classes/wp_query/#category-parameters
We are going to use the category__in and category__not_in parameters. And we will be fetching the category id via the category slug using get_category_by_slug.
Here is our final result. I've added comments, you can add more arguments of you want by looking at the CODEX to view the full list. Modify and have fun!
<?php
// Column A
$x = get_category_by_slug( 'category_x_slug' )->term_id; // ... get category x ID
$y = get_category_by_slug( 'category_y_slug' )->term_id; // ... get category y ID
$args = [
'post_type' => 'post'
'posts_per_page' => 6,
'category__in' => [ $x, $y, ], // ... Column A: post with category x, category y
];
$query = new WP_Query( $args ); // ... loop start
if( $query->have_posts() ):
while( $query->have_posts() ): $query->the_post();
// ... post template start
the_title( '<h1>', '</h1>' );
the_excerpt();
// ... post template end
endwhile;
else:
echo "No posts yet!";
endif; // ... loop end
wp_reset_postdata(); ?>
<?php
// Column B
$x = get_category_by_slug( 'category_x_slug' )->term_id;
$y = get_category_by_slug( 'category_y_slug' )->term_id;
$args = [
'post_type' => 'post'
'posts_per_page' => 6,
'category__in' => [ $x, ], // ... Column B: post with category x
'category__not_in' => [ $y, ], // ... Without post with category y
];
$query = new WP_Query( $args ); // ... loop start
if( $query->have_posts() ):
while( $query->have_posts() ): $query->the_post();
// ... post template start
the_title( '<h1>', '</h1>' );
the_excerpt();
// ... post template end
endwhile;
else:
echo "No posts yet!";
endif; // ... loop end
wp_reset_postdata(); ?>

Wordpress - get tags for posts with custom field

I have a custom field, say, "mood", and I need to display list of tags for all posts that have "mood" = "grumpy". Is it possible to do this without fetching all posts and then fetching tags for each of them?
You can use the function get_posts();
$args = array(
'meta_key' => 'mood',
'meta_value' => 'grumpy',
);
$your_posts = get_posts( $args );
Untested, but this should achieve what you want. Just look out for typos and missed semi-colons!
While you don't get the whole post, you do still have to query the database for the ID of posts with 'mood' = 'grumpy', so unless you have lots of posts, it's probably easier to just go with the answer #Dorel gave.
$query = $wpdb->prepare('
SELECT ID
FROM %1$s
LEFT JOIN %2$s
ON %1$s.ID = %2$s.post_id
WHERE %2$s.meta_key = "mood"
AND %2$s.meta_value = "grumpy"
', $wpdb->posts, $wpdb->postmeta
);
$ids = $wpdb->get_col($query);
if(!empty($ids)) : foreach($ids as $post_id) :
$tags = wp_get_post_tags($post_id, $args);
if(!empty($ids)) : foreach($tags as $tag) :
$tags[] = $tag->name;
endforeach;
endif;
endforeach;
endif;
// Now you have an array of Tag names, output them as you wish
Codex for wp_get_post_tags = http://codex.wordpress.org/Function_Reference/wp_get_post_tags
Codex for wp_get_object_terms (to see what $args are available for wp_get_post_tags) =
http://codex.wordpress.org/Function_Reference/wp_get_object_terms#Argument_Options

Query post using post id

SSomeone can tell me what's the best way to get a post using it's id?
I'am using this:
$query = query_posts('post_id='.$_GET['php_post_id']);
global $post;
foreach ($query as $post):
do stuff...
This is returning an array with all post
get_post( $post_id, $output );
So in practice will look like:
$my_id = 7;
$post_id_7 = get_post($my_id);
Further reference about the post's parameters and fields, here: http://codex.wordpress.org/Function_Reference/get_post
Update: It's the best practice when you need to get a single post by id, no cicles required.
Change post_id= to p=.
$setQuery = 'p='.$_GET['php_post_id'];
query_posts($setQuery);
Click in this link to see: Retrieve a Particular Post
If you are looking to get a single post with an ID you already know or getting from another source, i'll suggest the below code.
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'p' => $id, // id of the post you want to query
);
$my_posts = new WP_Query($args);
if($my_posts->have_posts()) :
while ( $my_posts->have_posts() ) : $my_posts->the_post();
get_template_part( 'template-parts/content', 'post' ); //Your Post Content comes here
endwhile; //end the while loop
endif; // end of the loop.
You can create a query like so:
$rd_args = [
'ID' => $postId
];
$query = new WP_Query($rd_args);
And then you can retrieve the post from the query. Or set it to the global query and loop over it:
$GLOBALS['wp_query'] = $query;
while ( have_posts() ) : the_post();
Here is the code to fetch post using query_post if you know the ID.
<?php
$my_query = query_posts('post_id=111&post_type=parks'); // in place of 111 you need to give desired ID.
global $post;
foreach ($my_query as $post) {
setup_postdata($post);
the_title();
the_content();
}
?>

How to get the Post number in wordpress

I am creating a new wordpress theme for my friend. I want to know how to get the "post number" of a particular post. I don't want the total count of posts. For example, Post No.1 , Post No. 2 etc., Very similar to page numbers in a book.
The wordpress post ID is generally random and i couldn't use it.
any help ?
thanks,
karthik.
EDIT: THIS WORKS.
Okay, so this works. thanks to this. This function will return '1' for 'first post', '2' for 'second post' and so on..
function Get_Post_Number($postID){
$temp_query = $wp_query;
$postNumberQuery = new WP_Query(array ( 'orderby' => 'date', 'order' => 'ASC', 'post_type' => 'any','posts_per_page' => '-1' ));
$counter = 1;
$postCount = 0;
if($postNumberQuery->have_posts()) :
while ($postNumberQuery->have_posts()) : $postNumberQuery->the_post();
if ($postID == get_the_ID()){
$postCount = $counter;
} else {
$counter++;
}
endwhile; endif;
wp_reset_query();
$wp_query = $temp_query;
return $postCount;
}
you can use this to display the number.
<?php $currentID = get_the_ID(); ?>
<?php $currentNumber = Get_Post_Number($currentID); ?>
<?php echo $currentNumber; ?>
If you are in the loop that displays posts, you can use get_the_ID() to return the post's id. If you are outside the loop and you have the post in $post, you can do $post->ID.

Wordpress - related posts by custom taxonomy problem

I'm trying to display related posts based on a custum taxonomy. I found a query at wordpress.org that kind of works. However the original post gets duplicated in the results multiple times. (words is the name of the custom taxonomy I use) What seems to happen is that the single post gets duplicated according to what amount showpost is set. Any idea's what could cause this?
The code:
<?php
//for in the loop, display all "content", regardless of post_type,
//that have the same custom taxonomy (e.g. words) terms as the current post
$backup = $post; // backup the current object
$found_none = '<h2>No related posts found!</h2>';
$taxonomy = 'words';// e.g. post_tag, category, custom taxonomy
$param_type = 'words'; // e.g. tag__in, category__in, but genre__in will NOT work
$post_types = get_post_types( array('public' => true), 'names' );
$tax_args=array('orderby' => 'none');
$tags = wp_get_post_terms( $post->ID , $taxonomy, $tax_args);
if ($tags) {
foreach ($tags as $tag) {
$args=array(
"$param_type" => $tag->slug,
'post__not_in' => array($post->ID),
'post_type' => $post_types,
'showposts'=>5,
'caller_get_posts'=>1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<h3><?php the_title(); ?></h3>
<?php $found_none = '';
endwhile;
}
}
}
if ($found_none) {
echo $found_none;
}
$post = $backup; // copy it back
wp_reset_query(); // to use the original query again
?>
It's inside the foreach loop that you're getting duplications. That code is effectively saying;
Get all the terms for taxonomy type $param_type
For each term, get 5 posts that are tagged with that term
So if you have a post that is tagged with more than one term of the same taxonomy, it's likely it will appear more than once.
You can iteratively add queried posts into the post__not_in array to ensure they don't appear again;
Add $post_not_in = array($post->ID); just above if ($tags) {
Then replace the line post__not_in' => array($post->ID), with post__not_in' => $post_not_in,.
Finally, drop $post_not_in[] = get_the_ID(); inside your while loop, after $found_none = '';
As for me i use this plugin for custom taxonomy relate post. I hope that plugin will help your problem.

Resources