Query post using post id - wordpress

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

Related

Wordpress - Get all users who commented on a post

I need to get all users who commented on a post. And for each user the comments. Searched online but couldn't find any solution.
If post_id= 15 then
<?php
$comments = get_comments('post_id=15');
foreach($comments as $comment) :
echo($comment->comment_author .'--coment--'.$comment->comment_content);
echo '<br>';
endforeach;
?>
see this for further details https://codex.wordpress.org/Function_Reference/get_comments
.
You need get_comments().
Here is how you get all comments on a certain post:
<?php
$args = array(
'post_id' => 0, // Place post ID here.
);
get_comments( $args );
?>
After running this code, you will get an array of posts and user IDs, you can use the IDs with a foreach to get all comments for each user. Like this:
<?php
$args = array(
'user_id' => 0, // Place user ID here.
);
get_comments( $args );
?>
You can get comment writer from its comment id:
<?php $author = get_comment_author( $comment_ID ); ?>
You can generate short code use it, Here this will display all information of comment.You need to extract which one is required.
function input_func( $atts ) {
global $post;
$comments = get_comments( array( 'number' => 2, 'post_id' => get_the_ID() ) );
print_r( $comments);
}
add_shortcode( 'input', 'input_func' );
Code:
global $wpdb, $post;
// Query
$query = sprintf("SELECT comment_author_email
FROM {$wpdb->comments}
JOIN {$wpdb->posts} ON {$wpdb->posts}.ID = {$wpdb->comments}.comment_post_ID
WHERE comment_post_ID = %d AND comment_approved = '1'",
$post->ID);
$emailslist = $wpdb->get_col($query);
$emailslist = array_unique($emailslist);
// get all emails
print_r($emailslist);
Here you can get list of emails of users.
You can also use WP_Comment_Query

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/

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

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