WordPress get specific posts in arbitrary order - mysql

Right now, I'm doing:
$posts = get_posts(array('post_type' => 'page', 'post__in' => array(1, 3, 2, 9, 7)));
and am having two issues:
Post 3 is of 'post_type' => 'post', so it doesn't get selected, but I want it! If I leave out 'post_type' => 'page', then only post 3 is selected (because it must assume 'post_type' => 'post'.).
I want to be able to order the posts arbitrarily by their ids. If I knew how to use MySQL, I could do:
SELECT * FROM wp_posts WHERE ID IN (1, 3, 2, 9, 7)
ORDER BY FIND_IN_SET(ID, '1,3,2,9,7');
But, how should I do this with WordPress?

First fetch all posts arbitrarily by their ids and then loop through all the posts
You can do in this way:-
$posts=$wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE ID IN (1, 3, 2, 9, 7)
ORDER BY FIND_IN_SET(ID, '1,3,2,9,7')");
$count=count($posts);
for ($counter=0 ; $counter < $count; $counter++)
{
$post=get_post( $posts[$counter]->ID, $output );
//do your stuffs with posts
}
Hope this helps

Kawauso on the #wordpress IRC channel informed me that "post_type takes an array of values." From that, I found that the following also selects post 3:
So, I did the following:
$post_ids = array(1 => 0, 3 => 1, 2 => 2, 9 => 3, 7 => 4);
$posts = get_posts(array('post_type' => array('post', 'page'),
'post__in' => array_keys($post_ids)));
$ordered_posts = array(0,0,0,0,0); // size of five; keeps order
foreach ($posts as $p) {
setup_postdata($p);
$ordered_posts[$post_ids[$p->ID]] = array(
'permalink' => get_permalink($p->ID),
'title' => $p->post_title,
'excerpt' => get_the_excerpt(),
'date' => date('F j, Y', strtotime($p->post_date)));
}

According to this thread, you can use this code and then use the classic WordPress loop:
$args = array(
'post_type'=>'page',
'orderby'=>'menu_order',
'order'=>'ASC'
);
query_posts($args);

Related

Yii2. How to build subexpression

How can i build query with subexpression, without using yii\db\Expression and raw sql. For example this:
SELECT * FROM user WHERE archived = 3 AND ((group = 2 AND status = 3) OR (group = 3 AND status = 2));
You can build such condition using array expressions:
$users = (new Query())
->from('user')
->where(['archived' => 3])
->andWhere([
'or',
[
'group' => 2,
'status' => 3,
],
[
'group' => 3,
'status' => 2,
],
])
->all();

CakePHP 3.6 Query Builder complex OR conditions issue

I am trying to build a query using query builder with complex nested AND and OR conditions. Here is what I have written so far.
$cond_arr = array();
$cond_arr['VehicleBrandModels.status'] = 1;
$query = $this->VehicleBrandModels->find();
$query->hydrate(false);
$query->select($this->VehicleBrandModels);
$query->where($cond_arr);
$VBM_data = $query->toArray();
This will generate a query like below
SELECT * FROM vehicle_brand_models WHERE status = 1;
I want to generate a query with nested AND & OR conditions like below
SELECT * FROM vehicle_brand_models WHERE status = 1 AND ((overall_rating > 0 AND overall_rating < 2) OR (overall_rating >= 2 AND overall_rating < 4) OR (overall_rating >= 4 AND overall_rating <= 5));
Can anybody help to solve how to achieve this in CAKEPHP 3.0 Query builder?
The simplest solution is the following
$cond_arr = [
'VehicleBrandModels.status' => 1,
'OR' => [
['overall_rating >' => 0, 'overall_rating <' => 2],
['overall_rating >=' => 2, 'overall_rating <' => 4],
['overall_rating >=' => 4, 'overall_rating <=' => 5]
]
];
there is a more 'cake' way and if I'll have time I will post it.
But note that from what I see all your OR conditions overlap and you can simply do
$cond_arr = [
'VehicleBrandModels.status' => 1,
'overall_rating >' => 0,
'overall_rating <=' => 5
];
edit: as primised here's the more cake way using query expressions
$query->where(function($exp, $q) {
$exp = $exp->eq('VehicleBrandModels.status', 1);
$conditions1 = $exp->and_([])
->gt('overall_rating ', 0)
->lte('overall_rating ', 2);
$conditions2 = $exp->and_([])
->gt('overall_rating ', 2)
->lte('overall_rating ', 4);
$conditions3 = $exp->and_([])
->gt('overall_rating ', 4)
->lte('overall_rating ', 5);
$orConditions = $exp->or_([$conditions1, $conditions2, $conditions3]);
$exp->add($orConditions);
return $exp;
});
still some conditions are overlapping

I want to pull data from an array in specific sequence using FIND_IN how?--never recived a right answer

Below is my code and I want to pull the data based on the sequence 3, 10 then 7, how can I do that? so far it pulls first 10, then 7, then 3.
$cars = $this->car->find('all', array(
'conditions' => array(
'car.id' => array(3, 10, 7)
),
'limit' => 3,
'order' => array('car.id' => 'desc')
));
Where do the conditions come from? Anyway i believe this will work:
$cars = $this->car->find('all', array(
'conditions' => array(
'car.id' => array(3, 10, 7)
),
'limit' => 3,
'order' => array('FIELD(car.id,3,10,7)')
));
Might need to play around with the cakePHP specific syntax, but the ORDER BY FIELD(fieldname, value, value value); should work

elastic search: Advanced Filter Query

I am Working on Elastic Search for My current Project. I need a filter for users based on their industries. please look at my code once. and mySql query as follows
SELECT U.* FROM `users` `U`
JOIN `user_industries` `UI` ON `UI`.`user_id`=`U`.`id`
WHERE `UI`.`industry_id` IN('1','3','5');
$query = array("from" => $start,
"size" => $recordslimit,
"sort" => array(array('id' => 'desc')),
"query" => array(
"filtered" => array(
"query" => array("match_all" => array()),
"filter" => array(
"bool" => array(
'must' => array(array('term' => array('user_type' => 'v')),
array('term' => array('status' => 'a')),
array('term' => array('industries.id' => 1))
),
'must_not' => array(
array('term' => array('subscription_type' => 'n'))
)
))
)));
I passed one Industry Value. how can i pass multiple values of industries
Great start !! You can achieve what you want by using a terms filter instead of a term one and specifying the values 1, 3, 5 in an array():
...
array('terms' => array('industries.id' => array(1, 3, 5)))
...

How to transform this array in a json?

I have this relation CompanyhasMany Branch
And using $this->Company->find('all') output this:
(int) 1 => array(
'Company' => array(
'id' => '4',
'nome' => 'Somov',
'diretores' => 'Marcelo, Carl'
),
'Branch' => array(
(int) 0 => array(
'id' => '3',
'nome' => 'Serra',
'rua' => 'Rua teste 2 exttttt',
'numero' => '22',
'estado' => 'ES',
'cidade' => 'Etc',
'cep' => '',
'responsavel' => '',
'company_id' => '4',
'cnpj' => ''
)
)
),
(int) 2 => array(
'Company' => array(
'id' => '5',
'nome' => 'Soimpex',
'diretores' => ''
),
'Branch' => array()
)
)
I want to transform this in a json like this to use with Highchart:
[{
name: NAME OF COMPANY (nome),
data: NUMBER OF BRANCHS
}, {
name: NAME OF COMPANY (nome),
data: NUMBER OF BRANCHS
}]
How I do this convertion? Thanks
This will return a json object with only one result.
If we use previous example, can be done like this:
$arr = $this->Company->find('all'); // fetch the array
$arr1 = array();
foreach ($arr as $value) {
$tmp = array();
$tmp['name'] = $value['Company']['nome'];
$tmp['data'] = count($value['Branch']);
$arr1[] = $tmp;
}
return json_encode($arr1);
<?php
$sql=mysql_query("select * from Posts limit 20");
$response = array();
$posts = array();
while($row=mysql_fetch_array($sql))
{
$title=$row['title'];
$url=$row['url'];
$posts[] = array('title'=> $title, 'url'=> $url);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
?>
This will generate a file called results.json file where your php file is stored on your online server, taking url and title variables from your MySQL db, you can change the variable names to what you want to fetch.
The whole idea is about like this
$arr=$this->Company->find('all'); // fetch the array
$arr1=array();
foreach ($arr as $value) {
$arr1['name']=$value['Company']['nome'];
//some more manual transform to desire format
}
return json_encode($arr1);