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
}
}
Related
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 would like to know the simplest way to add the value of the
$titles->post_title to become the key and value of an array.
Here is my code:
$data_from_database = array();
$titles = get_posts( array(
'post_type' => 'resort',
'order' => 'ASC'
) );
foreach($data_from_database as $field_key => $field_value) {
$field['choices'][$field_key] = $field_value;
$field['choices'][$field_value] = $field_value;
}
Desired result:
$data_from_database = array('1value' => '1value', '2value' => '2value',
'3value' => '3value');
I have looked and read other posts about this but wasnt able to find any info to achieved what i want to do.
Thanks for your answers in advance
Your question is completely unclear so try to add more details to get more complete answers.However based on you desired output
$data_from_database = array('1value' => '1value', '2value' => '2value',
'3value' => '3value');
and this:
I would like to know the simplest way to add the value of the
$titles->post_title to become the key and value of an array.
you can alter your code to look like this:
$data_from_database = array();
$titles = get_posts( array(
'post_type' => 'resort',
'order' => 'ASC'
) );
foreach($titles as $field_key => $field_value) {
$data_from_database[$field_key] = $field_key;
}
Try this code to get your desired output
$data_from_database = array();
$titles = get_posts( array(
'post_type' => 'news',
'order' => 'ASC'
) );
foreach($titles as $value) {
$data_from_database[$value->post_title] = $value->post_title;
}
Hope this helps you.
Thanks for the answers guys..
I figured it out by using this code.
$data_from_database = array();
$myarray = array();
$titles = get_posts( array( 'post_type' => 'resort') );
$new_title = wp_list_pluck($titles, 'post_title', 'post_title');
// reset choices
$field['choices'] = array();
// if has rows
foreach($new_title as $field_key => $field_value) {
$field['choices'][$field_key] = $field_value;
}
// return the field
return $field;
wordpress has a built in function to automatically push values and keys to an array
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;
}
I am working on a project to apply filters on wordpress post...I have created JSON Output and Now I need to apply 5 filters that are as follows..
1. All
2. Today
3. WeekEnd
4. Next Seven Days
5. Date wise
Flow of the whole process...GEt Posts data in JSON--> Fetch This Data --> Create Filters---> User can Then Search as well as filter Data Further with normal wordpress functions....But I am not able to work out for fetching out posts by applying the Next Seven days filter and weekEnd..as the issue seems to be at my way of fetching the posts...What I am doing for now is
Code for Next Seven Days or last seven days...
<?php
require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
//require_once("config.php" );
require_once("incformfunctions.php");
if($_SERVER['REQUEST_METHOD'] == "GET"){
$numberposts = isset($_REQUEST['numberposts']) ? $_REQUEST['numberposts'] : "-1";
$posttype = isset($_REQUEST['posttype']) ? $_REQUEST['posttype'] : "";
$securitycode = $_REQUEST['securitycode'];
$mode = $_REQUEST['mode']? $_REQUEST['mode'] : "ALL";
$taxonomy='art_categories';
if($securitycode == $secret)
{
$category_data=array();
if($mode=='recommended') //to get recommended post of posttype category
{
$args= array(
'numberposts' => 100,
'category' => 0,
'orderby' => 'date',
'order' => 'DESC',
'include' => array(),
'exclude' => array(),
'meta_key' => '',
'meta_value' =>'',
'post_type' => 'events', //post name
'suppress_filters' => true,
'date_query' => array(
array(
'key' => 'event_start_date', //custom name start date
'after' => '1 week ago'
),
),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'event_editors_choice', //custom name event editor
'value' => true
),
'relation' => 'AND',
array(
'key' => 'event_recommended', //custom name event recommended
'value' => true
),
),
);
}
$myposts = get_posts( $args); // get all value in array
if($myposts) {
foreach ( $myposts as $post ) : setup_postdata( $post ); //and using foreach loop show all post type field
$image= get_the_post_thumbnail_url();
$featured_image =wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ));
$start_date= get_post_meta($post->ID,'event_start_date',true);
$start_date=date('F j, Y', strtotime($start_date));
$end_date = get_field('event_end_date', $post->ID, false);
$end_date=date('F j, Y', strtotime($end_date));
$event_type = get_field('event_type', $post->ID, true);
$event_venue = get_field('event_venue', $post->ID, true);
$event_venue_address = get_field('event_venue_address', $post->ID, true);
$latitude = get_field('event_venue_latitute', $post->ID, true);
$longitude = get_field('event_venue_longitude', $post->ID, true);
$description_long = get_field('event_description_long', $post->ID, true);
$description_short = get_field('event_description_short', $post->ID,
true);
$gallery_address = get_field('gallery_address', $post->ID,
true);
if($gallery_address==false)
{
$gallery_address="";
}
$event_gallery = get_post_meta($post->ID,'gallery_address', true);
$venue_address= get_field('venue_address',$event_gallery,true);
$venue_postcode= get_field('venue_postcode',$event_gallery,true);
$venue_city= get_field('venue_city',$event_gallery,true);
$venue_location= get_field('venue_location',$event_gallery,true);
if($venue_location==false)
{
$venue_location="";
}
$venue=get_post_custom($post->ID);
$category=get_the_category($post->ID); //category
$excerpt=get_the_excerpt( $post );
$posttypes=get_post_type( $post );
$category_data[] = array('id' => get_the_ID (),'title' => get_the_title(),'excerpt' =>$excerpt,'featured_image' =>$featured_image,'image' =>$image,'event_type' =>$event_type,'event_venue' =>$event_venue,'event_venue_address' =>$event_venue_address,'event_latitude' =>$latitude,'event_longitude' =>$longitude,'start_date' =>$start_date,'end_date' =>$end_date,'posttypes' =>$posttypes,'tags'=>$tags,'description_long'=>$description_long,'description_short'=>$description_short,'venue'=>$event_gallery,'gallery_address'=>$gallery_address,'venue_address'=>$venue_address,'venue_postcode'=>$venue_postcode,'venue_city'=>$venue_city,'venue_location'=>$venue_location); // getting in all post array formate
wp_reset_postdata();
endforeach;
$data = $category_data;
$errcode=100;
$errstr='success';
}
else {
$errcode=-1;
$errstr='Post not found please check again..';
}
}
//for securitycheck
if ($securitycode !=$secret or $securitycode=='')
{
$errstr="unauthorise access";
}//end
}
else{
$errcode=-2;
$errstr='Request method not accepted';
}
#mysql_close($conn);
/ Output header /
#header('Content-type: application/json');
echo json_encode(array('errcode'=>$errcode,'errstr'=>$errstr,'data'=>$data)); // json create
die();
Any Help on what I am doing wrong??
I'm clearly not doing this right. Any help would be greatly appreciated. Essentially i am pulling nearby zip codes and city names to a search that is being done. i then want to use WP_Query to pull the WordPress post types matching those zip codes and city names. I'm not super familiar with WordPress, so it is highly likely i'm way off base on how to do this:
$url = "http://www.zipcodeapi.com/rest/OeAp3k78myEhBy0oqSlQSlUWOt6N7TjW8Tlbdtkz1YRCwS1WKmNDIHzwbFjizCeI/radius.json/" . $searchbox . "/100/km";
$response = file_get_contents($url);
$json = json_decode($response);
$post_type = 'location';
$citysearcharray = array();
$zipsearcharray = array();
$searcharray = array();
foreach($json->zip_codes as $nearbyzip)
{
$citysearcharray[] = array(
'key' => 'city',
'value' => $nearbyzip->city,
'compare' => '='
);
$zipsearcharray[] = array(
'key' => 'zip_code',
'value' => $nearbyzip->zip_code,
'compare' => '='
);
}
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'caller_get_posts'=> 1,
'posts_per_page' => 10,
'meta_query' => array(
'relation' => 'OR',
$citysearcharray,
$zipsearcharray));
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$count=0;
echo '<ul class="location">';
while ($my_query->have_posts()) : $my_query->the_post();
...
Amy i putting the $args together correctly?
TIA
In your foreach, instead of adding new full values to your arrays
$zipsearcharray
and
$citysearcharray
have the value key as an array so:
'value' => array(array of cities)
then change
compare => 'IN'