I have a custom post type called "books".
This post type has a custom field called "release-date" that contains a unix timestamp.
I'm working on WordPress archive.php page to have a list of books and I'm trying to alterate the main query.
What I need is to have only books with release-date > today and sorted by release-date.
This is what I try to sort it:
global $query_string;
query_posts( $query_string . "&meta_key=release-date&orderby=meta_value_num&order=ASC&posts_per_page=9" );
The sorting seems not working as expected.
I think that by now you should use the WP_Query class:
$args = array(
'post_type' => 'books',
'meta_query' => array (
'key' => 'release-date',
'value' => date('d/m/Y',strtotime("today")),
'type' => 'DATE',
'compare' => '>='
),
'meta_key' => 'release-date',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
and then, just
$your_query = new WP_Query( $args );
if ($your_query->have_posts()) {
while ( $jobs_query->have_posts() ) {
$your_query->the_post();
var_dump($post)
}
}
More info here
So if u want only post where release-date is bigger than today you can do an easy wp-query to get all post:
function getPostsByQuery(WP_Query $query)
{
$posts = array();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$posts[] = $query->post;
}
wp_reset_postdata();
}
return $posts;
}
function getPostsByCustomemField($name, $limit = -1)
{
return getPostsByQuery(new WP_Query(array('post_type'=>'books','meta_key' => $name, 'posts_per_page' => $limit)));
}
function getBooks() {
$posts = getPostsByCustomemField('release-date');
$books = [];
foreach ($posts as $post) {
if (get_post_meta($post->ID,'release-date',true) > date('d/m/Y',strtotime("today"))) {
$books[] = $post;
}
}
return $books;
}
Related
I have about 25,000 posts here (and rising). All of them under a Custom Post Type "lead".
Each post has meta information, including a variable called "uniqid".
this uniqid is a url parameter. now i need the post id where exactly this uniqid exists.
Now my question is if there is a way to speed up this determination.
I have tried 2 ways once a wp_query and get_results.
I ask because this function that determines the post id is always noted by plugin "query monitor" that it is slow.
These are the 2 approaches, both work. I just wonder if it is possible to speed up here?
The WP_Query solution.
$post_id = false;
$args = array(
'posts_per_page' => -1,
'post_type' => 'lead',
'fields' => 'ids',
'orderby' => 'date',
'order' => 'ASC',
'post_status' => 'publish',
'meta_key' => 'uniqid',
'meta_value' => $uniqid
);
$query = new WP_Query( $args );
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// Get Post ID for return
$post_id = get_the_id();
// Break loop, when matching id was found
$uniqidGPM = get_post_meta( $post_id, 'uniqid' , true );
if($uniqidGPM == $uniqid) {
$post_found = true;
break;
}
}
}
wp_reset_postdata();
return $post_id;
The select get_results solution.
$post_id = false;
global $wpdb;
$selectQuery = "SELECT wp_wkdm_posts.ID FROM wp_wkdm_posts INNER JOIN wp_wkdm_postmeta ON ( wp_wkdm_posts.ID = wp_wkdm_postmeta.post_id ) WHERE 1=1 AND ( ( wp_wkdm_postmeta.meta_key = 'uniqid' AND wp_wkdm_postmeta.meta_value = '".$uniqid."' )) AND wp_wkdm_posts.post_type = 'lead' AND ((wp_wkdm_posts.post_status = 'publish')) GROUP BY wp_wkdm_posts.ID ORDER BY wp_wkdm_posts.post_date ASC";
$selectQueryResult = $wpdb->get_results($selectQuery);
if (empty($selectQueryResult)) {
return $post_id;
}else{
$post_id = $selectQueryResult[0]->ID;
return $post_id;
};
Please use this meta_query condition on the same query, it helps you.
$args = array(
'post_type' => 'lead',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
'key' => 'uniqid',
'value' => 'YOUR_VALUE'
)
);
$query = new WP_Query($args);
I make a request to my custom endpoint function in functions.php :
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/homepage/', array(
'methods' => 'GET',
'callback' => 'custom',
) );
} );
And in return I get an array of posts of an author id :
function custom( $data ) {
$posts = get_posts( array(
'author' => $data['17'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts;
}
I want to return all posts and all categories but I get an error :
return [$posts , $categories ];
How can I get All posts and all categories in a single array inside custom function ?
You do all of that like this :
function custom( $data ) {
$posts = get_posts( array(
'post_type' => 'post'
'author' => $data['17'],
'numberposts' => -1
) );
$categories = get_categories();
return [$posts, $categories];
}
Ok try this
function custom( $data ) {
$posts = get_posts( array(
'post_type' => 'post'
'author' => $data['17'],
'numberposts' => -1
) );
$categories = get_categories();
return [$posts, $categories];
}
I'm using polylang plugin to having multi-languages website.
Using WooCommerce with polylang demands duplicating each product for each language, so assuming I have Hebrew and English, that means 2 duplications for each products.
It works fine with WooCommerce plugin, but when I'm displaying "related products" at the end of the product page, it's mixing products in English and Hebrew together.
I expect to filter the related product by website current language (if(get_locale() == 'en_US') - to check website current locale state, else will represent Hebrew).
Polylang functions
Here is what I have tried, but I got stuck on the part of filtering the product by language:
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
How can I filter Woocommerce related product section by language?
Edit
So after a little bit of research and help in the comments I found out that 'lang' => 'en' argument does exist, but even when I use it, there is no change on related products language display.
Any ideas?
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query,
'suppress_filters' => false
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
suppress_filters There is a way to make get_posts cache the results however, the suppress_filters option is true by default, but if you set it to false, the caching mechanisms inside WordPress will do their work, and results will be saved for later.
You can try this code:
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'meta_query' => $meta_query,
'lang' => 'en'
) );
if ($related_posts) {
foreach ($related_posts as $post) {
setup_postdata($post);
// something like <li><?php the_title(); ?></li>
}
}
wp_reset_postdata();
This code correctly returns code in selected language on my site
While working on a custom WordPress REST Api end point to fetch post by selected language or device language, this worked. See if it can help you out.
function mycustomplugin_posts($params) {
// get the url params
$page = $params->get_param('page') ? $params->get_param('page') : 0;
$per_page = $params->get_param('per_page') ? $params->get_param('per_page') : 10;
$offset = $params->get_param('offset') ? $params->get_param('offset') : 0;
$order = $params->get_param('order') ? $params->get_param('order') : 'desc';
$order_by = $params->get_param('order_by') ? $params->get_param('order_by') : 'date';
$lang = array_search($params->get_param('lang'),polylang_json_api_languages(), true) ? $params->get_param('lang') : pll_default_language();
$args = [
'post_type' => 'post',
'page' => $page,
'numberposts' => $per_page,
'offset' => $offset,
'order' => $order,
'orderby' => $order_by,
'tax_query' => [
[
'taxonomy' => 'language',
'field' => 'slug',
'terms' => $lang
]
]
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
// Extract the post data
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['excerpt'] = e42_the_short_content($post->post_content, 300);
$data[$i]['slug'] = $post->post_name;
$data[$i]['date'] = $post->post_date;
$data[$i]['link'] = get_permalink($post->ID);
$data[$i]['author'] = get_the_author_meta('display_name', $post->post_author);
$data[$i]['categories'] = array();
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$data[$i]['featured_image']['medium'] = get_the_post_thumbnail_url($post->ID, 'medium');
$data[$i]['featured_image']['large'] = get_the_post_thumbnail_url($post->ID, 'large');
foreach(get_the_category($post->ID) as $category){
array_push($data[$i]['categories'],$category->term_id);
}
$i++;
}
// Create the response object
$response = new WP_REST_Response( $data );
// Add a custom status code
$response->set_status( 200 );
return $response;
}
/plugins/woocommerce/templates/single-product/related.php
Move this to child theme
yourtheme/woocommerce/single-product/related.php
And add the following line to the foreach loop
if (pll_current_language()!=pll_get_post_language($post_object->ID)) {
continue;
}
Basically if current language does not match product language we skip over it.
I have an array of Wordpress page parent IDs which I then use a FOREACH loop to replace each parent ID with the name of the page (parent).
The problem is the array is sorted by the ID order, and I Want to now re-order it using the titles.
How can I do this?
function bv_quick_select_get_category_options() {
$procedure_pages = get_posts(array(
'post_type' => 'page',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => 'template-procedure-minimal.php'
)
)
));
$procedure_categories = array();
foreach($procedure_pages as $p1) {
array_push($procedure_categories, wp_get_post_parent_id($p1->ID));
}
$output = '';
foreach(array_unique($procedure_categories) as $c) {
$output .= '<option value="'.get_post($c)->post_title.'">'.get_post($c)->post_title.'</option>';
}
return $output;
}
I would think it would be more efficient to fetch the categories with one query based on the ids, and do the sorting by title in the database. This is my best attempt at how to do that from a quick read of the wordpress docs, but I'm not a wordpress user so it probably needs some work.
function bv_quick_select_get_category_options() {
$procedure_pages = get_posts(array(
'post_type' => 'page',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => 'template-procedure-minimal.php'
)
)
));
$ids = array_column($procedure_pages, 'ID');
$categories = get_posts([
'include' => $ids,
'order_by' => 'title'
]);
$output = '';
foreach($categories as $c) {
$output .= '<option value="'.$c->post_title.'">'.$c->post_title.'</option>';
}
return $output;
}
I have been struggling for a couple days with trying to use the data in a custom field to return posts. Here is my function that I have in functions.php. I am able to return my posts, except that they aren't limited to the ones defined in the $json variable. I can decode the json and return the array...but I can't seem to convert it in such a way that it fills in my array properly for the "posts__in" in the $dishes_arg.
Can anyone help me identify what I am doing wrong?
add_action ('woo_loop_before', 'hgf_home_menu');
function hgf_home_menu () {
if (is_home() || is_front_page()) {
wp_reset_query();
global $posts;
$menu_args = array(
'post_type'=>'single_menu',
'posts_per_page' => 1,
'meta_key' => 'orderby_date',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'orderby_date', // Order-By Date field is upcoming
'value' => date("Y-m-d"),
'compare' => '>='
),
array(
'key' => 'orderby_date', // Order-By Date isn't more than two weeks out
'value' => date("Y-m-d", strtotime( "+2 weeks")),
'compare' => '<='
)
),
);
// Get menu that meets criteria
$menus = new WP_Query( $menu_args );
// Show menu that meets criteria
if ( $menus->have_posts() ) {
while ( $menus->have_posts() ) {
$menus->the_post();
}
wp_reset_postdata();
// Get the menu's product/post listing
$json = '[{"id":"435"},{"id":"527"},{"id":"563"},{"id":"568"}]';
$array = json_decode($json);
$include = array();
foreach($array as $a) {
$include[] = $a->ID;
}
$args = array(
'posts_per_page' => -1,
'include' => $include);
$posts = get_posts($args);
$dish_args = array(
'post_type' => 'product',
'post__in' => $posts,
);
// Get dishes in menu listing
$dishes = get_posts( $dish_args );
if ($dishes) {
foreach ($dishes as $dish) {
}
}
} else { // no posts found }
/* Restore original Post Data */
wp_reset_postdata();
}
}
You jSon property is id not ID
$include[] = $a->ID;
Should be
$include[] = $a->ID;
Where/why is there jSon here? Is this coming from something else.
Otherwise that could just be a simple delimitated list or even a normal PHP array.
I figured it out...turns out I just had to cut out a bunch of code that was getting in the way: $include = array() ... $args = array() ... $dish_args = array() ... $dishes = get_posts(). Here is the corrected portion:
$json = '[{"id":"435"},{"id":"527"},{"id":"563"},{"id":"568"}]';
$dishes = json_decode($json);
if ($dishes) {
foreach ($dishes as $dish) {
// Echo titles and permalinks
}
}