WordPress - Order by ACF date, date first, then empty fields last - php

I'm trying to order content by the dick picker provided by ACF.
order by date field
Dates in order of soonest(past/present) to farthest out (ASC ordering).
Then any post that meets the criteria but doesn't have a date set would be last.
I have the following Query arguments:
(
[post_type] => people
[posts_per_page] => 10
[paged] => 1
[meta_query] => Array
(
[0] => Array
(
[key] => has_scheduling
[value] => 1
)
[1] => Array
(
[key] => custom_ID
[compare] => !=
[value] =>
)
[2] => Array
(
[key] => date_picker
[compare] => !=
[value] =>
)
)
[tax_query] => Array
(
[0] => Array
(
[taxonomy] => people_types
[field] => term_id
[terms] => 153
)
)
[meta_key] => date_picker
[orderby] => meta_value_num
[order] => ASC
)
I noticed that this Query will only load the first part correctly. It grabs content based on all the parameters, then orders is by date, but it excludes the content that doesn't have a date set.
I've tried this as well:
(
[post_type] => people
[posts_per_page] => 10
[paged] => 1
[meta_query] => Array
(
[0] => Array
(
[key] => has_scheduling
[value] => 1
)
[1] => Array
(
[key] => custom_ID
[compare] => !=
[value] =>
)
[2] => Array
(
[relation] => OR
[0] => Array
(
[key] => date_picker
[compare] => EXISTS
)
[1] => Array
(
[key] => date_picker
[compare] => NOT EXISTS
)
)
)
[tax_query] => Array
(
[0] => Array
(
[taxonomy] => people_types
[field] => term_id
[terms] => 153
)
)
[orderby] => meta_value
[order] => ASC
)
So here I don't exclude empty fields, I check if it exists and then doesn't. Then order by the data again. I also switched to use meta_value instead of meta_value_num
Any tips or tricks, or if you have run into issue as well, I'd love to see what you did.

For anyone also trying to do the same, the end result for this ended using a custom a orderby filter. Example code below.
// Order By custom date.
add_filter('posts_orderby', function (string $orderby, WP_Query $query) {
if ($query->get('orderby') === '__custom_date__') {
$orderby = "mta.meta_value is NULL, mta.meta_value ='', mta.meta_value ASC";
}
return $orderby;
}, 10, 2);
// Extra join to order by custom date.
add_filter('posts_join', function (string $join, WP_Query $query) {
if ($query->get('orderby') === '__custom_date__') {
$join .= " LEFT JOIN wp_postmeta AS mta ON ( wp_posts.ID = mta.post_id AND mta.meta_key = 'date_picker')";
}
return $join;
}, 10, 2);
This is then used as a parameter that gets passed to orderby
$args['orderby'] = '__custom_date__';

Related

How to get the data Using Yii2 Query Builder

What i am trying
I have 2 table staff and salarydetails,i want to fetch staff name and there respective salary
$salaries = SalaryDetails::find()->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$salaries->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$salaries->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
when i try to print sql raw query by using
echo $salaries->createCommand()->getRawsql();
i got SELECT salary_details.total_salary AS salary, staff.name AS name FROM salary_details LEFT JOIN staff ON salary_details.staff_id = staff.id
and this query gives the data i wanted in phpMyadmin
But the array gives ie, print_r($salaries); gives
yii\db\ActiveQuery Object ( [sql] => [on] => [joinWith] => [select] => Array ( [0] => salary_details.total_salary AS salary [1] => staff.name AS name ) [selectOption] => [distinct] => [from] => [groupBy] => [join] => Array ( [0] => Array ( [0] => LEFT JOIN [1] => staff [2] => salary_details.staff_id = staff.id ) ) [having] => [union] => [params] => Array ( ) [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ) [where] => [limit] => [offset] => [orderBy] => [indexBy] => [modelClass] => common\models\SalaryDetails [with] => [asArray] => [multiple] => [primaryModel] => [link] => [via] => [inverseOf] => )
Thanks,
As you can see in your print_r, $salaries is an ActiveQuery instance. Call the methods ->asArray()->all() on it to get the records.
$query = SalaryDetails::find()
->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$query->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$query->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
$salaries = $query->asArray()->all();
Note that without asArray the all would return an array of SalaryDetails records and you would loss the staff name.

How to get Maximum value from array inside array in php

I have my array like this, I want to fetch Score and Label from the array categories. I want to get my result like this as in here in category pornography its score is 0.25 and Non-Standard Content has score 0.1
so the result should be label=>'pornography' and score 0.25.
I tried getting values of label and score in an array like
$categories= array('pornography'=>0.25,'Non-Standard Content'=>0.1)
$value = max($categories);
then $value= 0.25
I want label also.
[text] =>
[taxonomy] => iab-qag
[language] => en
[categories] => Array
(
[0] => stdClass Object
(
[confident] =>
[score] => 0.25
[label] => Pornography
[links] => Array
(
[0] => stdClass Object
(
[rel] => self
)
[1] => stdClass Object
(
[rel] => parent
)
)
[id] => IAB25-3
)
[1] => stdClass Object
(
[confident] => 1
[score] => 0.1
[label] => Non-Standard Content
[links] => Array
(
[0] => stdClass Object
(
[rel] => self
)
)
[id] => IAB25
)
)
)
Somebody posted here Answer but I don't know why it is not appearing now. I used that solution to solve my problem here is the solution:
$maxScore = 0; $maxCat = [];
foreach($data[$x]->categories as $c) {
$cat[] = ['label' => $c->label, 'score' => $c->score];
if ($maxScore < $c->score) {
$maxScore = $c->score;
$maxCat = [
'label' => $c->label, 'score' => $c->score
];
}
Hope it will help somebody. Thanks to anonymous whoever posted this solution.

Sorting in Elastic Search by defined type

I have this request to elastic service.
Url callback is:
GET
/es-main/Project,ProjectStage,Task,TaskComment,TicketComment,Client,User,Attachment/_search
How to add Sort improvement requirements that the results were in sequence as they are embedded in the URL + score? Now alphabetically by type. Example first is type Project, second is ProjectStage, etc...
Thanks all for answers...
GET /es-main/Project,ProjectStage,Task,TaskComment,TicketComment,Client,User,Attachment/_search
Array
(
[query] => Array
(
[query_string] => Array
(
[query] => *a*
[analyzer] => hunspell_cs
[fields] => Array
(
[0] => name
[1] => description
[2] => tags.name
[3] => text
[4] => email
[5] => filename
)
)
)
[from] => 0
[size] => 10
[sort] => Array
(
[_type] => ASC
[_score] => DESC
)
[aggs] => Array
(
[CountByType] => Array
(
[terms] => Array
(
[field] => _type
)
)
)
)
Okey, i have added in document _is_Project = 1, _is_ProjectStage = ,_is_Task = 1, etc...
and set ordering to:
order: {
'_is_Project': {'unmapped_type': 'long'}, // first
'_is_ProjectStage': {'unmapped_type': 'long'}, // second
'_is_Task': {'unmapped_type': 'long'}, // third - etc...
'_score': 'DESC'
}

Change Index Key to Name

I have built a multidimensional array for usage in a custom Wordpress query. Although it is Wordpress I feel that this is more a basic PHP question.
The array that I have now outputs everything properly, accept for the index value. I need it to be a string instead of an integer.
Here is what I need my ouput to be
Array (
[post_type] => property
[posts_per_page] => -1
[tax_query] => Array (
[0] => Array (
[taxonomy] => state
[field] => slug
[terms] => illinois
)
[1] => Array (
[taxonomy] => illinois_county
[field] => slug
[terms] => fulton
)
)
)
And here is what is actually being output
Array (
[post_type] => property
[posts_per_page] => -1
[0] => Array (
[0] => Array (
[taxonomy] => state
[field] => slug
[terms] => illinois
)
[1] => Array (
[taxonomy] => illinois_county
[field] => slug
[terms] => fulton
)
)
)
The only difference being the key of the second array which is 0 in mine and needs to be tax_query.
To get this Array I am declaring $tax_query_array = array(); and then dropping my child arrays as needed depending on what variables are present in the url, such as $tax_query_array[] = $state_array; and $tax_query_array[] = $county_array;. Then finally calling $tax_query_array where i need the final multidimensional array output.
Only thing stopping me is the initial [0] which needs to instead be [tax_query].
Here is the full code:
$tax_query_array = array();
$tax_query_array['tax_query'][] = $state_array;
$tax_query_array['tax_query'][] = $county_array;
$tax_query_array['tax_query'][] = $price_range_array;
$taxonomy_args = array(
'post_type' => 'property',
'posts_per_page' => -1,
$tax_query_array
}
Output from changing $tax_query_array[] = $county_array; to $tax_query_array['tax_query'][] = $county_array; via MikeBrant:
Array (
[post_type] => property
[posts_per_page] => -1
[0] => Array (
[tax_query] => Array (
[0] => Array (
[taxonomy] => state
[field] => slug
[terms] => illinois
)
[1] => Array (
[taxonomy] => illinois_county
[field] => slug
[terms] => fulton
)
)
)
)
Try this code:
$taxonomy_args = array(
'post_type' => 'property',
'posts_per_page' => -1,
'tax_query'=> array($state_array, $county_array, $price_range_array)
}

code igniter form_dropdown() order

I am trying to order the dropdown items in alphabetical order but am unable to do so. I must be missing something obvious..
I assumed ORDER BY type_name would have created the array in alphabetical order
$data['training_types'] = $this->db->query("SELECT * FROM training_types ORDER BY type_name")->result_array();
print_r($training_types);
foreach ($training_types as $type)
{
$options[$type['id']] = $type['type_name'];
echo $options[$type['id']]; //test only: this displays the options in alphabetical order just fine
}
print_r($options);
echo form_dropdown('training_type',$options,'0');
//for some reason when the dropdown is created, the order is not alphabetical, it's not even ordered by id... I have no idea what is ordering it this way.
1st print_r returns:
Array ( [0] => Array ( [id] => 6 [type_name] => Independent Study ) [1] => Array ( [id] => 1 [type_name] => Instructor Lead ) [2] => Array ( [id] => 3 [type_name] => Instructor Lead/Virtual ) [3] => Array ( [id] => 7 [type_name] => Job Aid ) [4] => Array ( [id] => 5 [type_name] => Mentoring ) [5] => Array ( [id] => 2 [type_name] => Virtual ) [6] => Array ( [id] => 4 [type_name] => Web ) )
2nd print_r returns:
Array ( [2] => Virtual [3] => Instructor Lead/Virtual [4] => Web [1] => Instructor Lead [5] => Mentoring [6] => Independent Study [7] => Job Aid )
Can you print_r($data['training_types']) before the foreach loop and print_r($options) after the loop, and post results? This will help give insight as to what is going into the loop and what is coming out, to make sure it isn't the Form Helper form_dropdown() isn't reordering anything.
My suggestion is to just add a simple asort($options); before the form_dropdown() to insure it is alphabetical.
You didn't specify whether it's Ascending or Descending.
ORDER BY type_name ASC or ORDER BY type_name DESC

Categories