How to get the Post number in wordpress - 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.

Related

Wordpress: Previous/Next buttons on custom data types in meaningful order?

I have a website with 100 posts of a custom post type. On the single pages of each post, I would like to have a “Previous” and “Next” link to quickly jump to, you guessed it, the previous or next post.
I thought that was going to be easy, and I made these links:
<?php $prev_post = get_previous_post();
if ($prev_post) {
echo '<a rel="prev" href="' . get_permalink($prev_post->ID) . '">Previous</a>';
} ?>
<?php $next_post = get_next_post();
if ($next_post) {
echo '<a rel="next" href="' . get_permalink($next_post->ID) . '">Next</a>';
} ?>
Except those does not work. Instead of a hundred posts I can navigate through, it only allows me to jump through 5 posts. And random ones too: it goes from #1 to #15, then #40, #58, #80. Or if I decide to start from #100 and click previous, it goes to #79, then #40, #39 and #1.
It’s all very random. I have no clue what order this is and why it does not have all the posts.
Ideally I would like to go through the posts in alphabetical order of their slug. Ignoring taxonomy.
Anyone know how to do this? Thanks!
Looking more into it, I managed to solve it like that:
<?php
$criteria = array(
'post_type' => 'data_type',
'orderby' => 'slug',
'order' => 'ASC',
'posts_per_page' => -1
);
$posts = get_posts($criteria);
$ids = array();
foreach ($posts as $thepost) {
$ids[] = $thepost->ID;
}
$index = array_search($post->ID, $ids);
$previd = $ids[$index - 1];
$nextid = $ids[$index + 1];
if ($previd) { ?>
<a rel="prev" href="<?php echo get_permalink($previd) ?>">Previous</a>
<?php }
if ($nextid) { ?>
<a rel="next" href="<?php echo get_permalink($nextid) ?>">Next</a>
<?php } ?>
The limit of 5 posts was fixed with 'posts_per_page' => -1. The rest seems too complex for what is actually needed. If anyone knows of a simpler way closer to get_previous_post() I initially tried, I’m still interested.
Try this , but replace the post type.
if( get_adjacent_post(false, '', false) ) {
next_post_link('%link', '← Previous project');
} else {
$last = new WP_Query('post_type=project&posts_per_page=1&order=DESC'); $last->the_post();
echo '← Previous project';
wp_reset_query();
};
if( get_adjacent_post(false, '', true) ) {
previous_post_link('%link', 'Next project →');
} else {
$first = new WP_Query('post_type=project&posts_per_page=1&order=ASC'); $first->the_post();
echo 'Next project →';
wp_reset_query();
};

Wordpress - Custom plugin to return related posts by category

I'm learning how to create custom plugins for Wordpress, I am trying to get related posts by category.
The problem is, I am returning all posts regardless of it's category whether it's the same category or not.
I've done a var_dump on the $categoriesIds[] and it is pulling the right category for each post.
I'm guessing something is not right with the WP_Query?
Can someone point out what is missing with the code?
function Add_related_posts($content) {
// If it's not a singular post, return the content
if (!is_singular('post')) {
return $content;
}
// Get post categories
$categories = get_the_terms(get_the_ID(), 'category');
$categoriesIds = [];
foreach ($categories as $category) {
$categoriesIds[] = $category->term_id;
}
$loop = new WP_Query(array(
'category_in' => $categoriesIds,
'posts_per_page' => 4,
'post_not_in' => array(get_the_ID()),
'orderby' => 'rand'
));
// If there are posts
if ($loop->have_posts()) {
$content .= 'RELATED POSTS:<br><ul>';
while ($loop->have_posts()) {
$loop->the_post();
$content .= '<li>' . get_the_title() . '</li>';
}
}
$content .= '</ul>';
// Restore data
wp_reset_query();
return $content;
}
Categories are pulled as expected. But in argument in WP_Query, you got one problem.
It should be category__in, NOT category_in.
Try this:
'category__in' => $categoriesIds,
See documentation: http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

Check category in wp loop

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();

WP query looping through custom post type working on homepage but not on search page

I've got two custom post types called Artists and Paintings. Both the post types have a custom field called artist name created using Advanced Custom Fields plugin. I need to be able to match the custom fields from both these post types, with each other, in order to display more information.
Pasting below only the args and loop from the query. Will post more of the code if it is necessary.
<?php
$artist_name = get_field('artist');
$args = array(
'post_type' => 'artists',
'meta_value' => $artist_name
);
$query_artist = new WP_Query( $args );
if ( $query_artist->have_posts() ) {
while ( $query_artist->have_posts() ) {
$query_artist->the_post(); ?>
<p class="artist-name"><?php the_title(); ?></p>
<?php }
} else {
echo 'Artist not found';
}
wp_reset_postdata(); ?>
This code works properly when in the template file for the homepage but always prints out 'Artist not found' when in the search results page. I copied this code directly from the homepage template so spelling mistakes are not the problem. Been breaking my head over this for a long time. Will anyone reading this have a clue on what's happening?
Thanks.
Ok, so I've managed to finally get what I want to work but I'm not sure why the below code worked and my original didn't since both of them are similar methods to do a new query.
Here's the code if anyone else had the same problem:
<?php
// Permalink for artist
$artist_name = get_field('artist');
global $post;
$posts = get_posts( array( 'post_type' => 'artists', 'meta_value' => $artist_name ) );
if( $posts ):
foreach( $posts as $post ) :
setup_postdata($post); ?>
<p class="artist-name"><?php the_title(); ?></p>
<?php endforeach;
wp_reset_postdata();
endif; ?>
I think that wordpress doesn't include custom types in the search automaticaly.
You can use a plugin like https://wordpress.org/plugins/advanced-custom-post-search/ or write your own function in the functions.php
function rc_add_cpts_to_search($query) {
// Check to verify it's search page
if( is_search() ) {
// Get post types
$post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects');
$searchable_types = array();
// Add available post types
if( $post_types ) {
foreach( $post_types as $type) {
$searchable_types[] = $type->name;
}
}
$query->set( 'post_type', $searchable_types );
}
return $query;
}
add_action( 'pre_get_posts', 'rc_add_cpts_to_search' );
Example from http://www.remicorson.com/include-all-your-wordpress-custom-post-types-in-search/

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();
}
?>

Resources