I am trying to create a list of posts from a specific category inside a Wordpress page template by the function query_posts.
If I type in the category_name value directly in the query_posts' array value (for example 'category_name' => 'france-category') it IS working correctly.
But I would like to be able to define the category through a custom field in the page editor.
The get_field("custom-field") function retrieves the value I set in my custom field.
So I tried to put the value of my custom field into a variable and then retrieve the variable inside the array' value:
<?php
$category = get_field("france-category");
// The Query
query_posts( array ( 'category_name' => 'echo $category' ) );
// The Loop
while ( have_posts() ) : the_post();
the_title();
endwhile;
// Reset Query
wp_reset_query();
?>
But for some reason this isn't working. Is it not possible to use a variable within an array? Or Can anyone tell me whats else I am doing wrong?
In your code, try replacing 'echo $category' with just $category. Because you don't need to use the echo! Since the $category field would be having the value that you might have already fetched. So you could just pass that variable.
So, instead of this line:
query_posts( array ( 'category_name' => 'echo $category' ) );
try this:
query_posts( array ( 'category_name' => $category ) );
Related
I want to create a custom category (archive) page for a specific set of categories, adding some querystring vars.
So, I have an url like http://example.com/services/restaurants?city=gotham
If I don't modify WP_Query I have a correct list of services/restaurants but I want to add a filter by city, so if I use WP_Query like this then I get all services (not only restaurants), so it's not working as expected.
This is my code:
<?php
$categories = explode("/", get_query_var('category_name'));
$the_query = new WP_Query(array(
'post_type' => 'services',
'category_and' => $categories,
'meta_query' => [['key' => 'city', 'value' => $_GET['city']]]
)
);
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<?php the_title(); ?>
<?php
endwhile;
This is showing all services, not only restaurants even $categories is an array with [0] => 'restaurants'.
Note: if I use SAVEQUERIES and print all $wpdb->queries I can see the correct queries are logged, but then, after this queries, other queries for all services are applied.
How can I use WP_Query to get the category marked by url and add my own meta keys?
Thank you.
Just use at top of your archive.php
if( isset( $_GET['city'] && ''!= $_GET['city'] ) {
$city = $_GET['city'];
global $query_string;
$posts = query_posts($query_string."&meta_key=city&meta_value=$city");
}
It will modify the original query and append it
I want to have Wordpress post title in array.
I have my post titles in my custom post type as names of people with their surnames. I want to display my posts based alphabetically on their surnames and store it in an array. How do I do this in the loop?
You can retrieve the posts for your custom post type using WP_Query, and then run through each of them to get the titles.
// just get IDs rather than whole post object - more efficient
// as you only require the title
$post_ids = new WP_Query(array(
'post_type' => 'custom_post_type_name', // replace with CPT name
'fields' => 'ids',
'orderby' => 'meta_value',
'meta_key' => 'surname_field_name' // replace with custom field name
));
$post_titles = array();
// go through each of the retrieved ids and get the title
if ($post_ids->have_posts()):
foreach( $post_ids->posts as $id ):
// get the post title, and apply any filters which plugins may have added
// (get_the_title returns unfiltered value)
$post_titles[] = apply_filters('the_title', get_the_title($id));
endforeach;
endif;
Using WP_Query has the benefit that it does not alter the main loop on your page, and you can get the posts in the order that your require by using orderby along with the name of the custom field which contains the surname.
You can create an array outside the loop, then get the array filled up with the names, than sort the array.
<?php
// the array for the names
$name_array = array();
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
$name_array[] = $post->title;
//
// Post Content here
//
} // end while
if ( sizeof( $name_array ) > 0 ) {
sort( $name_array );
} // end if for sizeof()
} // end if
?>
If you cannot create the array outside The Loop, than you may move it under if ( have_posts() ) {.
Important note: this solution only contains the names in your current loop, so if your query does not hold all the posts, or is offset / paged, etc. then the array will not get all the names you have in your custom post type. If you would like to have all the names in the array and your loop query does not hold all the posts, then you have to query again - just for the titles (names).
trying to create woocommerce drop down list for all products
here's the code
thanks in advance
<select Name='choose'>
<?php
$args = array( 'post_type' => 'product' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) :
$loop->the_post();
echo '<option selected value="'.the_title().'</option>';
endwhile;
?>
</select>
You are doing a few things wrong.
Here's the correct way of outputting the options:
'<option value="'.the_title('','',false).'">'.the_title('','',false).'</option>'
Most likely you will need the post id as a the value and not the title itself, but that's besides the point.
the_title function by default echoes the result. We just want the value itself in this case. So we pass an empty string for the before and after params and a false for the echo param.
You could alternatively use the get_the_title function which is a cleaner way of doing the same.
Depending on your scenario, getting the information needed from the post object is more efficient. You would loop through the posts objects after you retrieve them like this: $loop->get_posts()
In category.php of a WordPress theme, you have the following loop:
if ( have_posts() ) : while ( have_posts() ) : the_post();
// output posts
endwhile; endif;
How do you go abouts outputting this exact same loop but with an offset? I found that you can change the loop by doing a
query_posts('offset=4');
But this resets the entire loop and the offset works but shows all the posts from every category, so I get the impression the query_posts completely resets the loop and does it with only the filter you add. Is there a way to tell the loop:
"do exactly what you're doing, except the offset make it 4"
Is this possible?
Thanks!
First of all don't use query_posts() see here instead use WP_Query
Try this:
//To retrieve current category id dynamically
$current_cat = get_the_category();
$cat_ID = $current_cat[0]->cat_ID;
$loop = new WP_Query(array(
'offset' => 4, //Set your offset
'cat' => $cat_ID, //The category id
));
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post();
// output posts
endwhile; endif;
Yes as Wordpress stated:
Setting the offset parameter overrides/ignores the paged parameter and
breaks pagination (Click here for a workaround)
Just follow the pagination workaround instructions and you're good to go.
I have an array of post IDs contained in $postarray. I would like to print the posts corresponding to these IDs in Wordpress.
The code I am using is as follows:
query_posts(array('post__in' => $postarray));
if (have_posts()) :
while (have_posts()) : the_post();
the_title();
the_excerpt();
endwhile;
endif;
Despite this, the loop prints the most recent posts and not the posts contained in the array. How can I have wordpress utilize the post IDs I supply in the array and print those posts in order?
You may have to break out of the standard WP Loop for this...
Try and use the get_post() function which takes the ID of a post and returns an object containing a the details of the post in the usual OBJECT or Associate or Numeric Array format.
See full-explanation of get_post().
You can come up with a custom routine to parse each item in the array. Here's a brief example:
function get_posts_by_ids( $postarray = null ) {
if( is_array( $postarray ) )
foreach( $postarray as $post ) {
$post_details = get_post( $post[0] );
// Title
echo $post_details->post_title;
//Body
echo $post_details->post_content ;
}
}
Hope this helps :)