Drupal views_embed_view sorting - php

I have a Drupal 7 module which includes a database query that gives me a list of jobs id's in a specific order based on calculated distance from a user-inputted location (nearest first, furthest last).
I then pass the job id's to views_embed_view as arguments with a contextual filter on the view. This then displays a list of jobs to the user.
However, whilst there is no sorting specified within the view, the order gets changed automatically. e.g. if the order of the records passed to views_embed_view is 10,52,22 it displays in the following order: 10,22,52 i.e. it gets ordered numerically ascending.
Any ideas on how to get views_embed_view to stop re-sorting my results?

Just thought I'd post how I solved it in case anyone encounters this issue in future:
A Drupal module called Views Arguments Extras includes a sort handler which allows for the order of items to be based on their order in a multi-value argument:
https://www.drupal.org/project/views_arguments_extras
Many thanks to the contributors of this module.

Related

Allow users to changer the sort order

How do allow users to change the order of posts, based on custom fields?
For example :
First custom field: Value1, second custom field: Value2.
In archive page, the posts are presented in order of the value 1 by default, and a filter (links) allows to order them according to the value 1 or 2.
Use the pre_get_posts hook as per the example here https://developer.wordpress.org/reference/hooks/pre_get_posts/#comment-2571. This assumes that your custom fields are stored as post_meta.
Note that you need to be very careful that you are only affecting the query that you want to affect at the time that you want to affect it. In this example they are checking that they are not in admin, that they only doing events (in your case you want posts) and that it is the main query (not another query that say a widget or some other function is running). Consider limiting it to the page that you want this to run on or putting the code in the theme template, so that it only runs for that template and not at any other time.

PHP - Sort and order an array of objects by category name

I am learning PHP and have decided to code my own OOP MVC framework. Now, I have realized several times already that it might not be the smartest move but I mean to see this out to the end. And then onwards...
My issue is creating a listing sidebar based on categories and a second based on year-month-postname.
I am officially stuck on the first one, let alone the second damn option. I have included some code and description of what I have tried. The lack of OOP info on the net is daunting or maybe it is because I am searching for the wrong thing, I dont know. But the tutorials have not given me any insight as to how to actually do this in a way where my database is in a model file and my class logic is in the class file.
Sorting logic should be like this Array-Object-Propertyname-Value.
The value, as I hope is easy to understand in my example below, is the category name eg Javascript, PHP, HTML. By that category i wish to sort my blog posts. But not in the way that requires me to manually input the category names to the code. I want to allow users to enter categories if they so choose.
I also wish to display the blog posts inside said category, lets say 5 most recent. But that should not be too hard with a
for($i=0,$i<5,i++)
nested inside whatever solution in the end will work for the category sort.
I have tried MySQLI procedural solutions ranging from multiple google searches and tutorials. Can do it, but dont want to do it procedurally. Tried foreach loop and nesting multiple foreach loops - simply cannot get either the problem of having duplicates based on the shared category name or if trying to group in the SQL query, it simply groups results with same category and then displays only the first one in the group. While loops with mysqli procedural work but with pdo in my case they produce infinite loops, no matter the condition I try to set.
So foreach is the way to go I believe. I have read up on loops and array sorting but I've yet to find a solution. I thought of sorting by key because that is what i need but to no applicable solutions.
It's easy to display the category names and dates and all that. But with category I always get duplicates.
Ive tried some logic where as to assign category names as variables but only to have them all be different variables, meaning still having duplicates or only rewriting the variable with each iteration.
Also, array sorts havent worked because I havent gotten any to work with sorting either on property or if converting Objects to a multidimensional array. Granted that may be because I am a beginner and not understood the syntax but I am not going to post them all here I think.
If you think an array sorting function will do the trick then perhaps give me an example and I will look into it with some new perspective hopefully.
PDO query :
'SELECT * FROM postTable
INNER JOIN userTable ON postTable.postUserId = userTable.id
INNER JOIN postCategories ON postTable.postCategoryId = postCategories.categoryName
ORDER BY postTable.postDate DESC'
Tried also to add
GROUP BY categoryName
but that resulted in only one entry per category shown when using var_dump. Sidenote - same is when grouping by creation date. Is there another layer added to the array when using group in the SQL command and I missed that in the docs?
PDO returns to view file :
$this->stmt->fetchAll(PDO::FETCH_OBJ);
this all gets passed into an array of
$results
and then that is sent to the php on the view page where the resulting array has this structure with var_dump.
array() {
[0]=>
object(stdClass)# () {
["categoryName"]=>
string() "Help"
}
[1]=>
object(stdClass)# () {
["categoryName"]=>
string() "Me"
}
and so on.
Note - also tried using -
fetchAll(PDO::FETCH_ASSOC);
But ive had similar failures with attempting any sorting or limiting to just one category name displayed but all entries under said category being displayed correctly and not just one per category.
I will be checking back when i finish work tomorrow so in about 20-22 hours from the time of posting.
If you need any more info just let me know and I'll post it.
You can order by multiple columns. Use:
ORDER BY categoryName, postDate DESC
This will keep all the posts in the same category together, and in decreasing date order within each category.
See How can i list has same id data with while loop in PHP? for how you can output the results, showing a heading for each category.
If you just want to get the 5 latest posts in each category, see Using LIMIT within GROUP BY to get N results per group?

Post meta values order in WordPress

i'm using custom fields in wordpress to store meta values. some custom fields have multiple values. i'm retrieving the array with "get post meta" which returns an array, as expected. but it seems the different items are ordered without any logic. some show up in the order they were entered, other's in opposite order, some total chaos.. what could i be missing?
i can't change the way the items are stored anymore.. there is too many entries in the database and the values show up perfect in the editing area but are stored in different order within the array.
This may or may not be possible. Wordpress is a bit like free energy machines - it violates a few useful concepts.
All your metadata is stored in the postmeta table. This table has a few fields: meta ID, post ID, meta key, value. Every time you add a meta, you add a row to this table. Every time you update a meta, however, you do not change the row order.
get_post_meta usually returns rows in the same order, so I am guessing you are doing some sort of sorting somewhere. Could we see some code? If it's always in ascending or descending but never as a random mix, you have a sort() lost somewhere.
I just recently had this same issue, here's what I found:
When you use get_post_meta(), WordPress checks if the meta data for the given object (post) has alreadby been loaded; if it has, then it's on the object cache (volatile, apc, memcached, etc) and load it's from there.
If the meta data it's not on the object cache, then it loads all the meta data for that object through update_meta_cache(), which queries the database without an ORDER BY
If your storage engine it's MyISAM, the results will be returned on a random order every time you update the meta data, but when using InnoDB the order in which the results are returned seems to be consistent (at least on my tests)

How to programmatically get magento category sort order

I am getting a collection of categories using
foreach(Mage::getModel('catalog/category')->getCollection() as $category)
For each of these categories, I need to retrieve the sort order. How do I do this?
The only function I can find that looks relevant in the category class is getDefaultSortBy(), which always returns news_from_date, which is neither the default sort order (position) or the selected sort order (price), so I don't know where that's getting its value from. I also noticed that if, in the magento backend, I change the list of available sort orders, the function getAvailableSortByOptions still always returns the same array. From these two facts, I conclude that the category functions must be accessing some sort of cross-category global settings, which is useless to me.
I want the specific sort order chosen for each specific category. Is there any way to retrieve this? Or do I need to write my own SQL? In that case, which table do I need to query?
I am using magento enterprise ver. 1.11.1.0
Found the answer. Naturally, moments after I posted the question!
The problem is that Mage::getModel('catalog/category')->getCollection() does NOT automatically load all of the category attributes. You have to indicate which ones to retrieve manually. So, I need to replace this:
foreach(Mage::getModel('catalog/category')->getCollection() as $category)
With this:
foreach(
Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('default_sort_by')
->addAttributeToSelect('available_sort_by')
as $category
)

PHP> Sort query results by name while letting each letter be on the top sometimes

I'm currently working on a site that will display a list of online shops,
Each shop will be stored on my database and I'll be using PHP to select and display them.
But since those shops will pay me, I want to let each shop to be on the top of the list sometimes,
(for example if the shop name starts with a "Z", they will probably complain for being on the bottom of the list all the time, so I want to keep it fair).
So I thought about letting each letter be on the top of the list for an hour, but i have no idea how to do that..
Is that even possible?
Thanks in advance!
I'd show a separate box and call it "today's pick" or something with just one shop in it. That way you can push the shops starting with "Z" to the top once in a while and at the same time keep the user experience of a list of shops which is sorted normally.
Then use the database to save which shop has been in the "today's pick"-box how many times to get them all up there equally.
There's no sane way (that I'm aware of) to handle this directly in SQL without adding a "priority" field to your schema (although it's possible, it would be convoluted at best). That said, here are two suggestions:
Modify your schema
Simply add a "priority" field to the relevant schema and sort by priority, name (or whatever the default is). You will of course need to reset the priority field every hour, but this is a fairly trivial task.
Handle it in PHP
Carry out the query as per usual.
Grab all the results into an array.
Re-prioritise as required based on the current hour. (You'll need to array_splice the item(s) you want to bump out of the array and then array_unshift them to the top.)
Output based on the array.
This will of course become more convoluted/less efficient if you need to handle pagination, but the basic idea is the same.
A nice solution would be to add another column to the database with the shop names, and call it something like "last_shown" then when you show this shop, update the column with a timestamp, and each select do something like:
"SELECT name,link FROM shops ORDER BY last_shown DESC"
then in php you could check
<?php
if($row['last_shown']+3600 > now()){
//run select but in ASC order
//update the new row's column to the current timestamp
}
?>
that way it will only update once an hour, but otherwise it will keep selecting the shop at the top of the list for the hour
sorry it's a bit of a mess i just typed this out quickly at work
You can add
1) a extra column as shown_times in schema
2) order by shown_times asc
3) & as a shop is shown you would +1
or
Another solution :
You can even use ORDER BY RAND()

Categories