Wordpress - related posts by custom taxonomy problem - wordpress

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.

Related

Wordpress standard loop: additional post count with parameters

I am altering a template file of the Search & Filter Wordpress Plugin to show additional post counts.
The plugin uses the standard Wordpress loop to query posts by certain parameters. The number of posts can be counted by using found_posts.
Now I want to display a second post count that takes additional parameters into account, eg. post_status. I have to stick to the regular WP loop to keep the query from the Plugin intact.
Something like this in the commented line:
if ( $query->have_posts() ) {
echo $query->found_posts 'posts found';
// echo $query->found_posts(array('post_status=>'private') 'private posts found';
while ($query->have_posts()) {
$query->the_post();
the_title();
}
}
The code works fine, except for the commented part which obviously doesn't work.
Is there a way to add another post_count with additional parameters to the standard loop?
Thanks
Georg
You could not add like this echo $query->found_posts(array('post_status=>'private') but before your loop just use below code to count posts by status. in your case you want to count posts by status private so add below code.
$args = array('post_type' => 'your_post_type_name','post_status' => array('publish', 'pending', 'draft', 'future', 'private', 'inherit', 'trash')
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
echo $query->found_posts 'posts found';
// echo $query->found_posts(array('post_status=>'private') 'private posts found';
$count_posts = wp_count_posts('post');
$private_posts = $count_posts->private;
echo $private_posts. 'private posts found';
while ($query->have_posts()) {
$query->the_post();
the_title();
}
}
similarly if you want to show count for publish or draft posts you can add below code.
$publish_posts = $count_posts->publish;
$draft_posts = $count_posts->draft;
you could count any other posts by its status is well.

Wordpress Posts Id from query_posts

I'm using WordPress with a template that generates a pretty nice thumbnail for each post depending on Ids, and type of post. (ref:https://blinkdemo.wordpress.com/)
Since I've been asked to create a custom page that could show certain post from a category, I decided to create a query for a template page that checks the page slug and then list the posts containing a certain category + a tag ('comparativas').
The problem that I'm facing is that the list of post presented on the page doesn't show up the corresponding thumbnail on each post.
Thumbnails are generated dynamically basically with these lines:
$post_id = $post->ID;
$thumbnail_id = get_post_thumbnail_id( $post_id );
$thumbnail_image = wp_get_attachment_image_src( $thumbnail_id,$thumbnail_size );
The problem is that I couldn't find the way to send to the specific post ids to the function above, since the main $wp_query->posts; retrieves the page id instead of the post requested by the query_posts method.
The loops present the correct posts but when I echo the post->ID it shows the page id.
My query is:
global $wp_query;
// concatenate the query
$args = 'cat='.$idCategory.'&tag=comparativas';
query_posts( $args );
$posts = $wp_query->posts;
$current_id = get_the_ID(); //-> this returns the page id
If you could please tell me how to overwrite the global $wp_query; so the template can handle the corresponding ids for the list of post It would be great.
Any clue?
Best,
Juan
You could use, setup_postdata($post)
Then get_the_ID() works again :)
It doesn't work just because you aren't looping through them. You can do it many ways.
The 2 more common are the following:
overwrite the query with query_posts
$args = array('cat' => $idCategory,'tag' => 'comparativas');
query_posts($args);
if(have_posts()){
while(have_posts()){
the_post();
$current_id = get_the_ID(); // this return what you want now
the_title(); // this works as expected
}
}
wp_reset_query(); // get previous query back
get an array of WP_Post objects and setup_postdata or simply loop through them
$args = array('cat' => $idCategory,'tag' => 'comparativas');
$posts_i_want = get_posts($args);
foreach( $posts_i_want as $post ){
setup_postdata($post);
$current_id = get_the_ID(); // this return what you want now
the_title(); // this works as expected
}
wp_reset_postdata(); // get previous postdata back
I personally prefer the first in most cases
Cheers

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/

Setting body id for custom post types in Wordpress

I have developed a function in functions.php to add a specific id to the body tag depending on the page template or the parent page template if it's a child page.
function get_body_id() {
global $post;
$parents = get_post_ancestors( $post->ID );
$parent_id = ($parents) ? $parents[count($parents)-1]: $post->ID;
$temp = get_page_template_slug($parent_id);
$path = pathinfo($temp);
$temp = $path['filename'];
switch ( $temp ):
case 'page-recipe-landing':
$id = 'bg-green';
break;
case 'page-home':
default:
$id = 'bg-pink';
break;
endswitch;
echo "id='".$id."'";
}
This works well for pages and their children but for my custom post types events/news and recipes this obviously will not return anything for get_post_ancestors( $post->ID ).
Is there a way to alter my function to cater for these custom post types or to assign custom post types to a specific 'page'?
Thanks for help with this.
<?php
if(empty($parents)) {
$loop = new WP_Query(array('post_type' => 'NAME_OF_TYPE', 'post_status' => 'publish'));
while($loop->have_posts()): $loop->the_post();
the_ID();
endwhile;
}
?>
This code should at least output the ID of each post with a custom type of NAME_OF_TYPE. If you wanted to store those in an array and work with them from there, the premise would be pretty much the same. I haven't tested the code, but it should work with custom post types.

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