I have a usermeta set up for my users that saves favorite post to their profile. I am getting this usemeta(which keeps the post IDs in it). Once I get it, I have it in an one dimensional array. I want to display a list of their favorite posts. I have tried this:
$favorites //array of favorites, that has come from the databese
$query = new WP_Query( array( 'post__in' => array( 2, 5, 12, 14, 20 ) ) );
and it would work fine, if I hard coded the post IDs , but since it is an array I can't just pass in array such, it returns nothing.
$query = new WP_Query( array( 'post__in' => $favorites) );
it does not accept it, I also tried to implode the array in to a string as such:
$fav_list = implode("," , $favorites);
and i get this, which is exactly what I need as a string
"124,126,125,130,132,140,142", without the quotes. I would then use it as such:
$query = new WP_Query( array( 'post__in' => array($fav_list) ) );
But again it doesn't work, it returns nothing. Since the favorites list is being pulled from the usermeta and the user can change it, I can't hard code the list.
Can anyone help me? Is it even possible with WP_Query. Not sure why it is not taking the string or what I am doing wrong. I red through the Wordpress Documentation but haven't found a solution.
Thanks in advance.
Arrays don't get stored in the database as arrays. They get serialized. When you pull the array from the database you have to unserialize() it.
http://php.net/manual/en/function.unserialize.php
If you var_dump($favorites) right after it comes out of the database, you'll notice it's a weird-lookin' string and not an array. var_dump(unserialize($favorites)) will show you your original array.
Related
I have created a custom field named "sec1array" in my categories so that i can add an array, for example 1,2,3,4
I want to retrieve that array and output it in the loop, so I created this code.
$seconearray = array($cat_data['sec1array']);
$args = array(
'post__in' => $seconearray
);
However, it only seems to be outputting the first post in the array. Is it something to do with the way the comma is outputting?
If I print $seconearray it outputs correctly, example 1,2,3,4
What you are doing is storing a string value of "1,2,3,4" in your database which when you are trying to construct an array from it like array("1,2,3,4") you end up just assigning a single value to that new array. This is why it only contains a single value.
You need to store your value in a serializable format so it can be converted back to an array after you save it to the database. There are many ways to do this, I'm sure others will give more examples:
JSON encode it
json_encode(array(1,2,3,4)); // store this in your db
json_decode($cat_data['sec1array']); // outputs an array
Or, you can use PHP serialize
serialize(array(1,2,3,4)); // store this in your db
unserialize($cat_data['sec1array']); // outputs an array
If you want to keep your string, you can explode it:
explode(',', $cat_data['sec1array']); // outputs your array of 1,2,3,4.
Using any of these methods will work. Finally you'll end up with an example like:
$seconearray = explode(',', $cat_data['sec1array']);
$args = array(
'post__in' => $seconearray
);
So I am building a WordPress theme for myself to meet my needs, so what I am looking for now is make a search using a get method in php.
If my url is something like this :
http://www.MyWordPressWebsite.com/search.php?string=Bananas+and+apples
In my search.php I would like to do something like this:
string = $_GET["string"];
$fruits_args = array(
'post_type' => 'fruits',
'posts_per_page' => -1,
'cat' => 'fruits'
);
$fruits = new WP_Query($fruits_args);
So how do I making the loop related to the string that I get from the the get method ?
comparing the search string the the post type, category and post title would be enough.
use query_posts() instead and Wordpress will handle the search with those parameters. You can add as many parameters as you want.
Example:
<?php $my_post_type = (get_query_var('my_post_type')) ? get_query_var('my_post_type') : false;?>
<?php query_posts(array('post_type' => $my_post_type));?>
<?php //Normal loop here ?>
For more info visit https://codex.wordpress.org/Function_Reference/query_posts
I hope this help
I'm trying to do a sort in my WP_Query on a custom field. The custom field contains strings such as "E100", "E500" and "E123b". I would like to sort numerically on these values, i.e. sort on the custom field as if the characters weren't there.
My query looks like this:
$subpages = new WP_Query(array(
"post_type" => "page",
"meta_key" => "[customFieldNameHere]",
"orderby" => "meta_value_num",
"order" => "ASC",
"posts_per_page" => 5000
));
But it doesn't work. It does some sort of sort, but it's not numerical. Is it possible to strip all characters/letters from the field, and then do a numerical sort on the remaining values, or is there some other way to solve this?
You can't sort a string with letters as if it were all numbers. If you try you will get a alphanumerical sort-- more or less what you'd do if you were alphabetizing something but it makes numbers look odd because it matches up all the first characters, then the second, and so on making numbers look like:
1
10
101
2
20
I don't know of anything built into MySQL that will do what you want, nor does WP_Query have any such feature. The best solution I have is to pull your results unsorted, and sort them later. You want to pull unsorted so the database doesn't do extra work.
$subpages = new WP_Query(array(
"post_type" => "page",
"meta_key" => "[customFieldNameHere]",
"posts_per_page" => 5000
));
$sorted = array();
foreach ($subpages as $s) {
$kname = preg_replace('/[^0-9]+/','',$s->customFieldNameHere]);
$sorted[$kname] = $s;
}
// you may need
// ksort($sorted);
var_dump($sorted);
One problem is going to be collisions. If you end up with two matching $knames you will clobber data, and frankly, that seems pretty likely if you have a lot of data.
I ended up removing the leading E from all strings. Doesn't really solve the original problem, with numerical sorting of strings, but at least it works now.
Problem with displaying news from database!
Screenshoot:
Database(table) Articals: ID, Title, Content, User
Very simple, i only want display last 3 news from database with foreach in view
(my controller send me array of 3 records in $artical, and this is ok), but view cannot
display this..
please help me, my dead line is tomorrow.
In cakephp if you put into your tables the field created and modified (DATETIME), the mvc automatically insert the date of creation or when you modify it.
So when you retrieve your data you can do in this mode
$articals = $this->Artical->find('all', array(
'limit' => 3,
'order' => 'Artical.created DESC' )
));
or in your case if you an increment id you can do in this mode (but I suggest you to use created and insert it into your tables)
$articals = $this->Artical->find('all', array(
'limit' => 3,
'order' => 'Artical.ID DESC' )
));
If you have some problem to print data try to make a var_dump($articals);
After try to print out your content like this:
foreach ($articals as $artical) {
echo '<p>'.$artical['Artical']['Content'].'</p>';
}
I want the user to be able to choose a restaurant from a dropdown list. I'm achieving this by the simple:
echo $this->Form->input(
'Restaurant', array('multiple'=>false, array('empty' => true)));
The issue I have is: some restaurants have duplicate names, and I need a way for the user to know which is which. I'd like to have the ID and/or address within the select options like:
<li value='62'>McDonalds (1234 Happy St) - #62</li>
<li value='63'>McDonalds (9876 French Fry Ln) - #63</li>
...etc
Is there a way to do this? I'm obviously capable of doing it w/ normal HTML, but... would be nice to stay in CakePHP.
Thanks ahead of time for any thoughts/suggestions/direction!
When you load your restaurants you're actually getting an array like this
array (
ID => NAME,
ID => NAME
)
Basically, it's an associated array with the ID as the key and the display field as the value. So as long as you modify that array via the find operation or via normal PHP array iteration, you can achieve your goal.
EDIT
So your answer is CakePHP VirtualFields
In your model you define it as
var $virtualFields = array(
'rest_unique_name' => 'CONCAT(Restaurant.first_name, " ", Restaurant.address)'
);
In your controller you do this
$opts = array(
'fields' => array('id', 'rest_unique_name')
);
$restaurants = $this->Restaurant->find('list', $opts);