I want to get all the posts in wordpress whose ids are passed in parameter like
http://localhost/wordpres/?pid=181,109,5,1
My front-page.php have following code
<?php while (have_posts()) : the_post(); ?>
<?php
if ('posts' == get_option('show_on_front')) {
get_template_part('content', 'posts');
} else {
get_template_part('content', 'page');
}
// If comments are open or we have at least one comment, load up the comment template
if (comments_open() || '0' != get_comments_number()) :
comments_template();
endif;
?>
<?php endwhile;} // end of the loop. ?>
And I have tried query_posts('p=181'); with http://localhost/wordpres/?pid=109 for single post; it works fine.
But I can't sort out how to give query_posts multiple post ids which are passed through url. Need help.
You can try this code existing above code to solve your problem.
<?php
$all_posts = sanitize_text_field($_GET['pid']);
if(!empty($all_posts)){
$all_posts = explode(',', $all_posts);
}else{
$all_posts = array();
}
$args = array(
'post_type' => 'post',
'post__in' => $all_posts
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
get_template_part('content', 'posts');
if (comments_open() || '0' != get_comments_number()) :
comments_template();
endif;
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
echo "no posts found";
}
?>
I did it by using following code
$thePostIdArray = explode(',', $_GET['pid']);
$args = array(
'post__in' => $thePostIdArray
);
query_posts($args);?>
<?php while (have_posts()) : the_post(); ?>
<?php
if ('posts' == get_option('show_on_front')) {
get_template_part('content', 'posts');
} else {
get_template_part('content', 'page');
}
Related
Hope you all be safe in this time of crisis. I'm looking for a solution to program my theme.. I do sometimes have content in my wordpress however i also does via a json. I wrote something but its throwing basic WP errors.
I need something like this but code correctly:
<div class="col-md-12">
<h3 class="h3">About {{ctrl.Coin.name}}</h3>
<?php
if ( have_posts() && get_the_content() != '') {
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/coindetail-content', get_post_type() );
endwhile; // End of the loop.
} else {
echo '<p ng-bind-html="ctrl.Coin.descriptionhtml"></p>';
}
?>
</div>
Who can help me with this?
Regards Dutch
Wrong function. You have to call have_posts() instead of have_post().
like:
$args = array(
'post_type' => 'coins', //post type name
'posts_per_page' => -1
);
$loop = new WP_Query($args);
if($loop->have_posts() && $loop->post_content != '') {
while($loop->have_posts()) : $loop->the_post();
get_template_part( 'template-parts/coindetail-content', 'coins');
endwhile; // End of the loop.
} else {
echo '<p ng-bind-html="ctrl.Coin.descriptionhtml"></p>';
}
?>
I'm using an AJAX search to pull 3 custom post types from wordpress (post, guides, advice). As you can see in my if while loop, the results show which results are which but I'm trying to section them out individually so it will show something like this:
section 1
blog posts
section 2
guides
The problem seems to be that I need to edit the if while loop because adding anything inside that loop will just cause it to be in that loop. Does anyone know the best way to modify the if while loop to achieve this?
function data_fetch(){
$the_query = new WP_Query(
array(
'posts_per_page' => 6,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
)
);
global $post;
if( $the_query->have_posts()) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<?php $type = get_post_type();
$term = $_POST['keyword'];
$i++;
$total = $the_query->found_posts;
?>
<span class="search-title">
<?php if ($type == 'post'):?>
<?php echo 'Article: ';?>
<?php elseif($type == 'guide' ):?>
<?php echo 'Guide: ';?>
<?php elseif($type == 'advice' ):?>
<?php echo 'advice: ';?>
<?php endif;?>
<?php the_title();?><br>
</span>
<?php endwhile; ?>
<?php
wp_reset_postdata();
else:
echo '<h3>No Results Found</h3>';
endif;
die();
}
If I were you, I'd probably just do three separate queries. They seem simple enough that it shouldn't cause any issues at all. Otherwise you have to either sort through or reorder the WP_Query results somehow.
If you're set on the single query, however - since these are such short HTML strings, I'd probably just control the output with the Output Buffer.
Basically you can create an associative array, and add the HTML strings to the appropriate keys. You could get a bit more elaborate and have them be nested arrays, but since your output is so light, you can probably get by just by having HTML strings as the values for the keys.
I took the liberty of cleaning up your code a little bit and removing some unused variables, etc.
function data_fetch(){
// Build the Query Arguments
$the_query = new WP_Query( array(
's' => esc_attr($_POST['keyword']),
'posts_per_page' => 6,
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
) );
// Do we have posts?
if( $the_query->have_posts()){
// We do. Start an array that will fill with HTML from the output buffer
$output = array(
'post' => '',
'guides' => '',
'advice' => '',
);
// Loop through the posts
while( $the_query->have_posts() ){
$the_query->the_post();
ob_start(); // Turn on the output buffer
$type = get_post_type(); ?>
<span class="search-title">
<?php echo ($type == 'post') ? 'Article: ' : ucwords($type).': '; // Output "Articles: " for posts, or just capitalize the other post type names ?>
<?php the_title();?><br>
</span>
<?php $output[$type] .= ob_get_clean(); // Add the HTML output from the buffer to our array
}
wp_reset_postdata();
// Here we have an array with 3 HTML strings that we can output wherever
echo $output['post'];
echo $output['guides'];
echo $output['advice'];
} else {
echo '<h3>No Results Found</h3>';
}
}
if I understood your concern, I propose to divide your code by creating a generic class.
and you make calls to the different Post Type :
class Custom_Query {
public $post_type;
public $key_word;
public function __construct($post_type, $keyword) {
$this->post_type = $post_type;
$this->key_word = $keyword;
}
public function getResult() {
echo '<h1>Article : ' . $this->post_type . '</h1>';
$the_query = new WP_Query(
array(
'posts_per_page' => 6,
's' => esc_attr($this->key_word),
'post_type' => array($this->post_type),
'post_status' => 'publish'
)
);
if ($the_query->have_posts()):
while ($the_query->have_posts()): $the_query->the_post();
echo '<span class="search-title">';
echo '' . the_title() . '<br>';
echo '</span>';
endwhile;
else:
echo '<h3>No Results Found</h3>';
endif;
wp_reset_postdata();
}
}
global $post;
$type = get_post_type();
$term = $_POST['keyword'];
$article = new Custom_Query($type, $term);
$article->getResult();
You were on the right track initially. You can just use the standard post objects to check for post type. You can adjust to fit your needs, but try something like this:
<?php
query = new WP_Query( array(
's' => esc_attr($_POST['keyword']),
'posts_per_page' => 6,
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
) );
if ($query->have_posts()) {
while ($query->have_posts()):
$query->the_post();
?>
<div class="posts">
<?php
if ($query->post->post_type === 'post') {
// add your content
} else if ($query->post->post_type === 'guides' {
// add your content
} else {
// add your content
}
?>
</div>
<?php endwhile;
} else {
// no posts found
}
I hace 2 sections on my site: first is for popular posts (based on views) and the second section is for the recent posts.
If the post is already in the popular posts section, I don't want it to be displayed in the "Recent posts" section. Below is my code. In the first loop I've created an array to store all post ID's which are in that section. In the second loop I check if the id is in that array (may be not the best solution).
For some reason it only works with the first duplicate, even though $cont becomes true required amount of times(I checked with echo). So what gives?
<?php
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) );
$counter=0;
$post_ids = array();
while ( $popularpost->have_posts() ) : $popularpost->the_post();
$postID = get_the_ID();
$post_ids[$counter] = $postID;
?>
<?php the_title(); ?>
<?php $counter++; ?>
<?php endwhile; ?>
<?php $myquery = new WP_Query('posts_per_page=6');
while ( $myquery->have_posts() ) : $myquery->the_post(); ?>
<?php $post_id = get_the_ID(); ?>
<?php $post_ids_length = count($post_ids); ?>
<?php for ($i=0; $i < $post_ids_length; $i++) {
if ($post_id == $post_ids[$i]) {
$cont = "true";
} else {
$cont = "false";
}
} ?>
<?php if ($cont == "true") {
continue;
} ?>
<?php the_title(); ?>
<?php endwhile; ?>
Update your Second Query as below:
$args2 = array('post__not_in' => $post_ids,'posts_per_page' => 6 );
$myquery = new WP_query($args2);
And then just iterate over the result using the While loop.
Sorry, I think I read every post about this but cant get it to work.
I have a Wordpress custom post typ called "external" and I would like to show both the post from "external" aswell as my normal standard posts at the same time on my homepage.
This is my loop:
<?php
get_header();
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(''); ?>>
<?php the_content(); ?>
</div>
<?php endwhile; wp_reset_postdata(); endif; ?>
How can I include the "external" posts in this code?
The theme then uses blocks to display content on the startpage, here is block8.php with a post query.
function block_eight_ajax_query($atts='') {
$args = array (
$is_ajax = 0;
if($atts==''){
$is_ajax=1;
$atts=$_GET;
if($atts['global_query']){
unset($atts['no_found_rows']);
unset($atts['suppress_filters']);
unset($atts['cache_results']);
unset($atts['update_post_term_cache']);
unset($atts['update_post_meta_cache']);
unset($atts['nopaging']);
}
}
$atts['is_ajax'] = $is_ajax;
$query = null;
$query = new WP_Query( $atts );
$html = '';
if ( $query->have_posts() ) {
ob_start();
$i = 1;
while ( $query->have_posts() ):
$query->the_post();
$atts['video'] = rd_field( 'abomb_post_video' );
$atts['extern'] = rd_field( 'extern' );
$atts['audio'] = rd_field( 'abomb_post_audio' );
$atts['gallery'] = rd_field( 'abomb_post_gallery' );
$atts['counter'] = $i;
block_grid_content($atts);
if ($atts['column'] == 'grid-12') { $divide = 1; }
else if ($atts['column'] == 'grid-3') { $divide = 4; }
else if ($atts['column'] == 'grid-4') { $divide = 3; }
else { $divide = 2; }
if ($i%$divide==0 && $divide!=1) {
echo '<div class="clear"></div>';
}
$i++;
endwhile;
if ($atts['nav'] == 'numbered') {
echo '<div class="grid-12">';
rd_pagination($query->max_num_pages);
echo '</div>';
}
wp_reset_postdata();
$html = ob_get_clean();
if($is_ajax==1){
echo $html;
exit();
}
return $html;
}
else{
if($is_ajax==1){
echo '-11';
exit();
}
return '';
}
}
Update: I added this code to functions:
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
if ( $query->is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'extern' ) );
return $query;
}
Now I can see the posts in for exampel the search result but I need the Query in Block8.php to fetch them aswell.
I Thanks!
To include a custom post type in the regular loop (ie. posts page) just add the following code to index.php before if ( have_posts() ) :
$args = array(
'post_type' => array('post', 'custom_post_type'),
'post_status' => 'publish',
);
$new_post_loop = new WP_Query( $args );
then modify the following two lines:
if ( have_posts() ) : change it to if ( $new_post_loop -> have_posts() ) :
and
while ( have_posts() ) : the_post(); to while ( $new_post_loop -> have_posts() ) : $new_post_loop -> the_post();
This solution avoids the problem of having the custom post type listed in the all posts screen on the backend, which #David.J's answer produces ;)
Add this to your functions.php file.
/**
* #param WP_Query $query
* #return WP_Query
*/
function add_my_custom_post_type( $query ) {
if ($query->is_main_query())
$query->set( 'post_type', array( 'post', 'external' ) );
return $query;
}
add_action( 'pre_get_posts', 'add_my_custom_post_type' );
Ref & duplicate: https://wordpress.stackexchange.com/questions/27104/how-to-display-regular-posts-custom-post-types-that-fall-under-a-category-usin
function add_my_custom_post_type( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
if ($query->is_main_query()) {
$query->set( 'post_type', array( 'post', 'some_custom_post_type_name' ) );
}
return $query;
}
}
add_action( 'pre_get_posts', 'add_my_custom_post_type' );
This is the correct way to write the code so as not to break the dashboard queries.
I have set up a few categories and want to display specific ones based on is_page().
Inside page.php, I've created an if..else statement that checks the page name and prints out the specific category. My problem at the moment is that instead of just the_title being printed out the whole post is being printed.
Where am I going wrong with this?
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php if ( is_page( 'Greywater Recycling' ) ) { ?>
<div class="col">
<?php query_posts( 'category_name=Greywater Recycling&posts_per_page=5'); if (have_posts()) : while (have_posts()) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; endif; ?>
</div>
<?php } else if ( is_page( 'Stormwater Management' ) ) { ?>
<div class="col">
<?php query_posts( 'category_name=Stormwater Management&posts_per_page=5'); if (have_posts()) : while (have_posts()) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; endif; ?>
</div>
<?php } else if ( is_page( 'Rainwater Harvesting' ) ) { ?>
<div class="col">
<?php query_posts( 'category_name=Rainwater Harvesting&posts_per_page=5'); if (have_posts()) : while (have_posts()) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; endif; ?>
</div>
<?php } ?>
<?php endwhile; // end of the loop. ?>
Many problems with your code. For one, is_page does not work inside the loop.
Second, don't mess with query_posts: When should you use WP_Query vs query_posts() vs get_posts()?. Really, forget about it for secondary loops.
Your code can be simplified to the following. In functions.php, we drop one function to get the Category ID by its Name. And another to do a secondary loop using the ID. And then, in page.php a simple call to those functions.
Documentation: Class_Reference/WP_Query.
page.php
Notice that you don't need to open PHP tags at each line, that makes the code dreadly difficult to read.
Use it only to swap between PHP and HTML
<?php
get_template_part( 'content', 'page' );
// This page title
$the_title = get_the_title();
// Search for category with the same name of the page
$category = brsfl_get_category_id( $the_title );
// Category found, go to the secondary loop
if( $category ) {
brsfl_check_print_categories( $category );
}
functions.php
Always prefix your function names with something distinctive to avoid conflicts that may take the site down.
/**
* Get the category ID based on its name
*/
function brsfl_get_category_id( $cat_name )
{
$term = get_term_by( 'name', $cat_name, 'category' );
// term found, return its ID
if( $term ) {
return $term->term_id;
}
// not found
return false;
}
/**
* Print a loop based on a category ID
*/
function brsfl_check_print_categories( $cat_id )
{
$args = array(
'post_type' => 'post',
'cat' => $cat_id,
'posts_per_page' => 5
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() )
{
while ( $the_query->have_posts() ) :
$the_query->the_post();
echo '<h2>' . get_the_title() . '</h2>';
endwhile;
}
else
{
echo 'No posts found...';
}
}
Although I've answered within the proposed scope, I think there are better solutions to this, like:
a shortcode, just adapt the functions.
using Advanced Custom Fields to show a meta box where you can select a very specific category (don't relying in page and category names) and use only the WP_Query function to print it out in the template.
i think it's better to get the category by the slug name.
i've tried your solution, it works fine but in the case of one of my category has a name with special html characters like apostrophes or quotes it doesn't.
here is the piece of code edited from your solution :
in your functions.php
function brsfl_get_category_id($cat_name){
$term = get_term_by( 'slug', $cat_name, 'category' );
if( $term ) {
return $term->term_id;
}
return false;
}
in your page.php
$the_slug = get_post(get_the_ID())->post_name;
$category = brsfl_get_category_id( $the_slug );
if( $category ) {
brsfl_check_print_categories( $category );
}