Wordpress query_posts result differs from wp_query request result - php

I have a multisite Wordpress setup (3.5.1, I cannot risk updating) on which I am querying some posts after having switched to the correct blog.
I have a query_posts function with the following parameters:
$posts = query_posts('posts_per_page=5&paged=1&post_status=publish&orderby=date&order=desc');
from this query of posts the query_vars becomes ($GLOBALS['wp_query']->query_vars):
Array (
[posts_per_page] => 5
[paged] => 1
[post_status] => publish
[orderby] => date
[order] => desc
[error] => [m] => 0
[p] => 0
[post_parent] =>
[subpost] =>
[subpost_id] =>
[attachment] =>
[attachment_id] => 0
[name] =>
[static] =>
[pagename] =>
[page_id] => 0
[second] =>
[minute] =>
[hour] =>
[day] => 0
[monthnum] => 0
[year] => 0
[w] => 0
[category_name] =>
[tag] =>
[cat] =>
[tag_id] =>
[author_name] =>
[feed] =>
[tb] =>
[comments_popup] =>
[meta_key] =>
[meta_value] =>
[preview] =>
[s] =>
[sentence] =>
[fields] =>
[menu_order] =>
[category__in] => Array ( )
[category__not_in] => Array ( )
[category__and] => Array ( )
[post__in] => Array ( )
[post__not_in] => Array ( )
[tag__in] => Array ( )
[tag__not_in] => Array ( )
[tag__and] => Array ( )
[tag_slug__in] => Array ( )
[tag_slug__and] => Array ( )
[ignore_sticky_posts] =>
[suppress_filters] =>
[cache_results] => 1
[update_post_term_cache] => 1
[update_post_meta_cache] => 1
[post_type] =>
[nopaging] =>
[comments_per_page] => 50
[no_found_rows] =>
)
The query Wordpress says it executes to find these posts is then ($GLOBALS['wp_query']->request):
SELECT SQL_CALC_FOUND_ROWS wp_5_posts.ID
FROM wp_5_posts
WHERE 1=1 AND wp_5_posts.post_type = 'post' AND (wp_5_posts.post_status = 'publish')
ORDER BY wp_5_posts.post_date desc LIMIT 0, 5
If I execute this query on the database the resulting IDs are:
12059
12046
12038
12030
12026
However, if I loop over the posts:
foreach($posts as $p){
echo($p->ID."<br>");
}
I get the following ID's:
11741
11721
11643
12059
12046
12038
12030
12026
Does anyone know how this is possible? The array $posts is empty before calling query_posts and I do not understand why these posts occur in the array. If I select these posts in my MySQL database by hand there is no noticeable difference between them that would make the first three special in some way, and all three are older than the other 5 requested.
Thanks in advance!

Did you try to see what post type are you getting on both queries? I remember once I had this issue where I was querying post using wp_query and query_posts and in one instance, I was getting only POSTs and in other instance I was getting all Pages / Media Attachment and Posts

Related

Tree listing for categorys

I have an array like this
Array
(
[0] => stdClass Object
(
[cat_id] => 3
[cat_name] => sample 3
[cat_description] =>
[cat_folder] => sample_3
[cat_path] => sample_3
[cat_parent] => 0
[cat_num_files] => 0
[cat_num_files_total] => 0
[cat_user_roles] =>
[cat_owner] => 1
[cat_icon] =>
[cat_exclude_browser] => 0
[cat_order] => 0
)
[1] => stdClass Object
(
[cat_id] => 2
[cat_name] => sample 2
[cat_description] =>
[cat_folder] => sample_2
[cat_path] => sample_3/sample_2
[cat_parent] => 3
[cat_num_files] => 0
[cat_num_files_total] => 0
[cat_user_roles] =>
[cat_owner] => 1
[cat_icon] =>
[cat_exclude_browser] => 0
[cat_order] => 0
)
)
I need to list these like
-sample 3
--sample 2
---sample 4
There is no limit for the link depth, a category may have 5 deep, it may be 10. I have tried this in a foreach loop but failed to retrieve a list like a tree.
I recommend recursion, becouse you don't know how nested it will be. Bellow is example of recursion function.
function genCat($parentCat){
echo $parentCat->name;
if ($parentCat->haveChildren){
foreach($parentCat->children as $child){
genCat($child);
}
}
}
This is just example, hope it helps

How does it works the Laravel 4 model relationships?

I wish to know how works the laravel 4 relationships in the model. This question is because i'm trying to get the rows from 2 tables with relation and not success till now.
class Products extends Eloquent {
protected $table = "Products";
protected $primaryKey = "ProductId";
public function plandetail()
{
return $this->belongsTo("PlanDetail", "PlanDetail.ProductId")->select( array("ProductId", "Order") );
}
public function getProductsPlan($dealerId)
{
return $this->with( "plandetail" )->where("Products.DealerId", $dealerId)->get();
}
} // end model
// In my controller
$product = new Products();
$products = $product->getProductsPlan($id);
foreach( $products as $product )
{
print_r($product); // prints only the rows from the Products table
// not the PlanDetail table.
}
In the output is just print the product records and not the PlanDetail table rows. Do i need to add a join with the PlanDetail table to get these rows?
This is one example row of what im getting now:
Products Object ( [table:protected] => Products [primaryKey:protected] => ProductId [errors:Products:private] => [rules:Products:private] => Array ( [ProductBaseId] => required|numeric [DealerId] => required|numeric [ProductName] => required|max:255 [DisplayName] => required|max:255 [Bullets] => required [Cost] => required|numeric [SellingPrice] => required|numeric [UseWebServicePricing] => required|boolean [Term] => required|numeric [Type] => required|numeric [Deductible] => required|numeric [VehiclePlan] => required|numeric [Mileage] => required|numeric [TireRotation] => required|numeric [Interval] => required|numeric [UseRangePricing] => required|boolean [IsTaxable] => required|boolean [NotRegulated] => required|boolean [CreatedOn] => required [CreatedBy] => required [ModifiedBy] => required [ModifiedOn] => required ) [connection:protected] => [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [ProductId] => 3 [ProductBaseId] => 84 [DealerId] => 50 [ProductName] => Vehicle Service Contract [DisplayName] => US Warranty Service Contract [ProductDescription] => [Bullets] => Warranty Proteccion for the covered components,Rental Car Coverage,Towling Coverage,, [Cost] => 0.0 [SellingPrice] => 0.0 [BrochureImage] => [PDFContrator] => [UseWebServicePricing] => 1 [UseManualPricing] => 0 [BrochureHeight] => 0 [BrochureWidth] => 0 [Term] => 36 [Type] => Platinum [Deductible] => 100 [VehiclePlan] => None [Mileage] => 36000 [TireRotation] => 0 [Interval] => 0 [PENProductId] => 0 [DMSProductId] => 16 [CreatedBy] => GREIVIN BRITTON [CreatedOn] => 2015-01-08 22:26:47.000 [UseRangePricing] => 0 [ModifiedBy] => GREIVIN BRITTON [ModifiedOn] => 2015-01-28 15:06:11.000 [IsTaxable] => 0 [NotRegulated] => 0 ) [original:protected] => Array ( [ProductId] => 3 [ProductBaseId] => 84 [DealerId] => 50 [ProductName] => Vehicle Service Contract [DisplayName] => US Warranty Service Contract [ProductDescription] => [Bullets] => Warranty Proteccion for the covered components,Rental Car Coverage,Towling Coverage,, [Cost] => 0.0 [SellingPrice] => 0.0 [BrochureImage] => [PDFContrator] => [UseWebServicePricing] => 1 [UseManualPricing] => 0 [BrochureHeight] => 0 [BrochureWidth] => 0 [Term] => 36 [Type] => Platinum [Deductible] => 100 [VehiclePlan] => None [Mileage] => 36000 [TireRotation] => 0 [Interval] => 0 [PENProductId] => 0 [DMSProductId] => 16 [CreatedBy] => GREIVIN BRITTON [CreatedOn] => 2015-01-08 22:26:47.000 [UseRangePricing] => 0 [ModifiedBy] => GREIVIN BRITTON [ModifiedOn] => 2015-01-28 15:06:11.000 [IsTaxable] => 0 [NotRegulated] => 0 ) [relations:protected] => Array ( [plandetail] => ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [appends:protected] => Array ( ) [fillable:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) [dates:protected] => Array ( ) [touches:protected] => Array ( ) [observables:protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 [softDelete:protected] => )
Thanks in advance :)
It looks like there's a few things wrong here.
The belongsTo method expects the name of the relating model, and then the foreign key of that model on the Products table. It looks like your foreign key is actually on the relating model making this relationship either a hasOne or hasMany. In this case, since you say you are expecting 2 rows, I'm assuming hasMany.
Additionally, the second argument of this only expects the name of the column. It can already guess the name of the table because you gave it the relating model name.
With that in mind, this should be the relationship method you need.
public function plandetails()
{
return $this->hasMany("PlanDetail", "ProductId")->select( array("ProductId", "Order") );
}
And the other function should be modified a bit. When you use with and you need to query based on the relation, you should pass in an array where the key is the name of the relation and the value is a callback function which will allow you to modify the query which will grab the relating items.
public function getProductsPlan($dealerId)
{
return $this->with(array("plandetail", function($q) use ($dealerId)
{
$q->where('DealerID', $dealerId);
}))->get();
}
Now when you do this...
$product = new Products();
$products = $product->getProductsPlan($id);
This should work...
foreach( $products as $product ) {
foreach($product->plandetails as $plandetail) {
print_r($plandetail);
}
}
I also modified the relating function name so you would have to update your getProductsPlan function to reflect that when you use with. When you use hasMany, it makes more sense and is easier to read when you make the function name plural.

Codeigniter: Referencing a specific array index returned in model result

I'm still trying to wrap my head around passing db query results from a model back to controller and finally to a view. I seem to be getting the data to the right place, I'm just not sure how to best access the resulting array of objects in the view.
Specifically, I'm trying to query my db for the most recent 7 distinct dates that someone has submitted a link. I get back an array of dates, and then for each of those dates I do a query for all links submitted on that date and store the results in an array. Then in the view, for each of those distinct dates, I show a header (the date), immediately followed by the links associated with it.
The array that come from my distinct date query ($link_headers):
Array (
[0] => stdClass Object([added_date] => 2011-08-11)
[1] => stdClass Object([added_date] => 2011-05-03)
[2] => stdClass Object([added_date] => 2011-04-21)
[3] => stdClass Object([added_date] => 2011-04-10)
[4] => stdClass Object([added_date] => 2011-03-04)
[5] => stdClass Object([added_date] => 2011-02-28)
[6] => stdClass Object([added_date] => 2011-02-22)
)
The array that comes from my query for actual links submitted ($links_result):
Array
(
[0] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1178
[link_url] => http://www.amazon.com/Silicone-Rubber-CASSETTE-Design-IPHONE/dp/B004YDJWOY
[link_name] => Silicone Skin BLACK CASSETTE TAPE
[link_notes] => iPhone case... probably won't fit in my dock.
[added_date] => 2011-08-11
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[1] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1177
[link_url] => http://snorby.org/
[link_name] => Snorby - Snort front-end
[link_notes] =>
[added_date] => 2011-05-03
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[2] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1176
[link_url] => http://www.nytimes.com/2011/04/17/business/17excerpt.html?_r=4&pagewanted=1&ref=business
[link_name] => Corner Office - The 5 Habits of Highly Effective C.E.O.s
[link_notes] => Sounds a lot like what Nathanial said...
[added_date] => 2011-04-21
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[3] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1175
[link_url] => http://chezlarsson.com/myblog/2010/06/panduro-concrete-challenge-3.html
[link_name] => Concrete book-ends
[link_notes] => Cool look...
[added_date] => 2011-04-10
[flag_new] => 1
[rating] => 4
[public] => 1
)
[1] => stdClass Object
(
[user_id] => 2
[link_id] => 1174
[link_url] => http://themeforest.net/item/reciprocity-photo-blog-gallery/154590
[link_name] => Site Templates - Reciprocity - Photo Blog
[link_notes] =>
[added_date] => 2011-04-10
[flag_new] => 1
[rating] => 5
[public] => 1
)
)
[4] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1173
[link_url] => http://lifehacker.com/#!5771943/the-always-up+to+date-guide-to-jailbreaking-your-ios-device
[link_name] => The Always Up-to-Date Guide to Jailbreaking Your iOS Device
[link_notes] =>
[added_date] => 2011-03-04
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[5] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1172
[link_url] => http://lifehacker.com/#!5754463/how-to-jailbreak-your-ios-421-device
[link_name] => How to Jailbreak Your iOS 4.2.1 Device
[link_notes] =>
[added_date] => 2011-02-28
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[6] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1171
[link_url] => http://www.bitplumber.net/2010/10/a-cassandra-hardware-stack-dell-c1100s-ocz-vertex-2-ssds-with-sandforce-arista-7048s/
[link_name] => A Cassandra Hardware Stack
[link_notes] =>
[added_date] => 2011-02-22
[flag_new] => 1
[rating] => 3
[public] => 1
)
)
)
... all seems fine enough. But my problem comes from my view, where I'm trying to build the HTML as described above. A simplified view of the code I'm trying to get to work is as follows:
foreach ($link_headers as $header) {
echo "INDEX: ". $links_headers .", ADDED DATE: ". $header->added_date ."<BR>";
foreach ($links_result[$link_headers] as $result){
echo $result->added_date ."<BR>";
echo $result->link_name ."<BR><BR>";
}
}
So, I'm trying to use the index of the first one to tell my foreach loop which index of the second array to loop through and get the content. Clearly I'm misusing the $links_result[$link_headers] variable(s) but I left it in to show what I was trying to do.
Any help is very much appreciated!
Michael
I dont use CodeIgniter but whether within th framework or from PHP i would just grab it all in one go and then the issue with the indexes becomes moot:
SELECT * FROM model_table mt WHERE mt.added_date IN (
SELECT DISTINCT md.added_date from model_table md
ORDER BY md.added_date DESC
LIMIT 7
) ORDER BY mt.added_date DESC
That should get you an array of models ordered by date limted to the 7 most recent dates. So then its just a matter of choosing when to display a header:
$current = null;
foreach($links as $link) {
if($link->added_date !== $current) {
// show the header and set current to the current date
$current = $link->added_date;
echo 'HEADER: Added on ' . $current . '<br />';
}
echo $row->added_date ."<BR>";
echo $row->link_name ."<BR><BR>";
}

How do I retrieve an item from an PHP Object Array?

I want to retrieve quantities from this array.
invoice Object
(
[data:private] => Array
(
[i_status] => pend
[i_title] => 500 HLCoins , 500 HLCoins x8
[i_member] => 1
[i_items] => Array
(
[0] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 1
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[extra] =>
[opt_id] => 0
[associated] =>
[assocBought] =>
[groupRenewals] => 0
[methods] => Array
(
)
[k] => 0
[_tax] => 0
)
[1] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 8
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[opt_id] => 0
[groupRenewals] => 0
[methods] => Array
(
)
[_tax] => 0
)
)
[i_total] => 0
[i_date] => 1347217384
[i_return_uri] =>
[i_paid] => 0
[i_status_extra] => a:1:{s:4:"type";s:4:"zero";}
[i_discount] => 0
[i_temp] =>
[i_ordersteps] => 0
[i_noreminder] => 1
[i_renewal_ids] => Array
(
)
[i_po] =>
[i_notes] =>
[i_shipaddress] =>
[i_id] => 229
)
[takeAction] => 1
)
I've tried a bunch of codes like $invoice->quantity, $invoice[1]->quantity, $this->$invoice->quantity, but none of them seem to display.
It still does not display at all, I tried to print_r and that is the array it gave me.
All the variables are private which means you cannot access them from outside the object. Check out the class definition for the invoice class. There should be some function to get the quantities from the object, or else you could add such a feature to the class.
The whole point of this is separation of concerns. The class may change in the future and possibly not use the same structure, therefore you should use object functions to access the properties, do not access them directly as variables.
You can read more on this subject in the manual or in a book about object-oriented programming.
Seems like all the data is in a private property. You cannot access it from outside directly.
Read the documentation for the class. It should have some method you can call, like getQuantity(), that'll get you the data. It depends on how the class was written and how it is supposed to be used.

Merge arrays from 2 SQL results

So i have a tags table setup in SQL
lists, lists_tags, tags
Each list can have multiple tags, and tags have two types genre and producer. Now if we are looking for all lists with tags 'action' these are the steps im following
SELECT GROUP_CONCAT(mini_lists_tags.list_id) AS list_ids
FROM (`mini_tags`)
LEFT JOIN `mini_lists_tags` ON `mini_lists_tags`.`tag_id` = `mini_tags`.`tag_id`
WHERE `mini_tags`.`tag_slug` = 'action'
That will return an array 1,2 for the ids of the list.
SELECT *
FROM (`mini_lists_anime`)
JOIN `mini_lists` ON `mini_lists`.`list_id` = `mini_lists_anime`.`list_id`
WHERE `mini_lists`.`list_id` IN ('1', '2')
AND `mini_lists`.`list_state` = 'active'
that gets all the lists in an array EXAMPLE:
Array
(
[0] => stdClass Object
(
[list_id] => 1
[list_episodes] => 13
[list_duration] => 24
[list_aired] => 1238623200
[list_age_rate] => PG-13 - Teens 13 or older
[user_id] => 1
[list_mal] => 5342
[list_category] => Anime
[list_type] => TV
[list_status] => Completed
[list_title] => Asura Cryin'
[list_alt_titles] => アスラクライン
[list_thumb] => 17071
[list_likes] => 0
[list_date] => 1300609723
[list_update] => 0
[list_state] => active
[list_info] =>
)
[1] => stdClass Object
(
[list_id] => 2
[list_episodes] => 26
[list_duration] => 23
[list_aired] => 1238623200
[list_age_rate] => PG-13 - Teens 13 or older
[user_id] => 1
[list_mal] => 329
[list_category] => Anime
[list_type] => TV
[list_status] => Completed
[list_title] => Planetes
[list_alt_titles] => プラネテス
[list_thumb] => 4822
[list_likes] => 0
[list_date] => 1300609723
[list_update] => 0
[list_state] => active
[list_info] =>
)
)
And then we get the tags
SELECT `mini_lists_tags`.`list_id`, `mini_tags`.`tag_type`, GROUP_CONCAT(mini_tags.tag_name) AS tag_names
FROM (`mini_lists_tags`)
INNER JOIN `mini_tags` ON `mini_tags`.`tag_id` = `mini_lists_tags`.`tag_id`
WHERE `mini_lists_tags`.`list_id` IN ('1', '2')
GROUP BY `mini_lists_tags`.`list_id`, `mini_tags`.`tag_type`
that gets all the tags in an array EXAMPLE:
Array
(
[0] => stdClass Object
(
[list_id] => 1
[tag_type] => Genre
[tag_names] => Supernatural,Action,Mecha
)
[1] => stdClass Object
(
[list_id] => 1
[tag_type] => Producers
[tag_names] => Seven Arcs
)
[2] => stdClass Object
(
[list_id] => 2
[tag_type] => Genre
[tag_names] => Romance,Action,Sci-fi,Comedy,Slice of Life,Drama,Space
)
[3] => stdClass Object
(
[list_id] => 2
[tag_type] => Producers
[tag_names] => Sunrise,Bandai Entertainment,Bandai Visual,Bang Zoom! Entertainment
)
)
Now the problem is I need to get them merged on the list_id so it returns something like this for each one.
stdClass Object
(
[list_id] => 1
[list_episodes] => 13
[list_duration] => 24
[list_aired] => 1238623200
[list_age_rate] => PG-13 - Teens 13 or older
[user_id] => 1
[list_mal] => 5342
[list_category] => Anime
[list_type] => TV
[list_status] => Completed
[list_title] => Asura Cryin'
[list_alt_titles] => アスラクライン
[list_thumb] => 17071
[list_likes] => 0
[list_date] => 1300609723
[list_update] => 0
[list_state] => active
[list_info] =>
[list_tags] => Array
(
[0] => stdClass Object
(
[tag_type] => Genre
[tag_names] => Mecha,Action,Supernatural
)
[1] => stdClass Object
(
[tag_type] => Producers
[tag_names] => Seven Arcs
)
)
)
Any advice is appreciated, i'm really lost. if there is better solution than this, i am all ears.
You can do another type of join that will return the parent item multiple times merged with each child object like so:
Array(
[0] => stdClass Object
(
[list_id] => 1
[list_episodes] => 13
[list_duration] => 24
...etc
[tag_type] => Genre
[tag_names] => Supernatural,Action,Mecha
...etc
)
[1] => stdClass Object
(
[list_id] => 1
[list_episodes] => 13
[list_duration] => 24
...etc
[tag_type] => Producers
[tag_names] => Seven Arcs
...etc
)
[2] => stdClass Object
(
[list_id] => 2
[list_episodes] => 26
[list_duration] => 23
...etc
[tag_type] => Genre
[tag_names] => Supernatural,Action,Mecha
...etc
)
[3] => stdClass Object
(
[list_id] => 2
[list_episodes] => 26
[list_duration] => 23
...etc
[tag_type] => Producers
[tag_names] => Seven Arcs
...etc
)
)
You will then need to loop through your results merging down the results into their child/parent relationships. This is because SQL always returns rows as results, not complex structures.
Although this is more complex to deal with, it's ususally less process intensive than making looped sql queries for each parent object (known as n+1 queries)

Categories