Primary and Secondary Sorting in Wordpress - arrays

I am creating a Wordpress theme that catalogs albums, and I have created the custom post type, created the custom fields, and have them successfully pulling in. I have several custom fields including; Artist, Album, Size, Label etc. I currently have the posts sorting alphabetically by the Artist name with this array:
$args=array(
'post_type' => 'albums',
'order' => 'ASC',
'meta_key' => 'custom_meta_artist',
'orderby' => 'meta_value',
'posts_per_page' => -1,
);
But I would also like the Albums, 'custom_meta_album', to sort alphabetically if it is the same Artist. Currently if a user enters in 10 albums by the same artist, the post will be alphabetized correctly by the Artist name, but the Albums have no order.
Is there a way to do some sort of second level sorting or primary and secondary sorting in Wordpress? I don't know if it's a IF statement that says "if artists value is equal then also sort albums ascending" or something along those lines. I figure there needs to be some way to tell Wordpress which field it should sort by first and then continue to the second level.

You may try this, hope this will work
// keep this function in your functions.php
function myCustomOrderby($orderby) {
return str_replace('menu_order', 'mt1.meta_value, mt2.meta_value', $orderby);
}
This is your args array
$args=array(
'post_type' => 'albums',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'custom_meta_artist',
'value' => '',
'compare' => 'LIKE'
),
array(
'key' => 'custom_meta_album',
'value' => '',
'compare' => 'LIKE'
)
)
);
add_filter('posts_orderby','myCustomOrderby'); // Add filter before you call the WP_Query
$albums = new WP_Query($args);
remove_filter('posts_orderby','myCustomOrderby'); // Remove filter after you call the WP_Query
// Start your loop
while ( $albums->have_posts() ) : $albums->the_post();
//...
endwhile;

Related

Wp_query items from array of id's at the beginning of the query

I have an array of items for example:
ids = array(112,113,114);
and have a wp_query that returns a list of posts including the posts with the id's listed in the ids array
I need to sort the wp_query posts o that will show the 112, 113, 114 then the rest of the posts from the query
I was thinking maybe I can sort the items by the ids array like this
$args = array(
'orderby' => ids,
'order' => 'ASC'
)
You should use post_in parameter so you can achieve the result as you want. below code will work.
$args = array(
'post_type' => 'your_post_type',
'posts_per_page' => -1,
'orderby' => 'post__in',
'order' => 'ASC',
'post__in' => array(112,113,114)
);
so above code will only order posts given in post_in parameter.
Tested and works well.

Getting data by search filter from associated models

i have an question regarding search filter in cakephp. Without complicating my question, below are the structure of what i want....
1) I have a projects table.
2) another one is project_funder_names table which is associated with projects table. project_id is in project_funder_names table. i have made project_funder_names table because i need multiple funder names for a single project, thats why i have made this table.
3) now the main point is i want if i search multiple funders in search filter which is coming in dropdown with checkbox, i will get project details according to these values. so how it would happen.
here is my cakephp find all query....
$project_info = $this->Project->find('all', array(
'conditions' =>
array(
'Project.status' => 1,
'OR' => array($search)),
'fields' => array('id', 'title', 'short_description', 'budget_allocation', 'currency', 'total_comments', 'published_date'),
'contain' => array(
'ProjectFunderName' => array(
'conditions' => array($search_funder)),
'Currency' => array('currency_symbol'),
'ProjectBookmark' => array('project_id', 'user_id')
)
)
);
problem is in $search_funder.
please help me for this.. thanks.
Looks like you need to search results based on associated models. One drawback of using containable behavior is if you're trying to assign a condition to an associated model, the main model will be retrieved no matter what.
In situations where you'd want to retrieve the main as well as the associated records based on a condition for the associated model, I'd suggest you to use join.
$joins = array(
array('table' => 'project_funder_names',
'alias' => 'ProjectFunderName',
'type' => 'LEFT',
'conditions' => array('ProjectFunderName.project_id = Project.id')
),
array('table' => 'currencies',
'alias' => 'Currency',
'type' => 'LEFT',
// It's unclear how currencies is associated with the other tables. Use appropriate table join condition here
),
array('table' => 'project_bookmarks',
'alias' => 'ProjectBookmark',
'type' => 'LEFT',
'conditions' => array('ProjectBookmark.project_id = Project.id')
)
)
);
$project_info = $this->Project->find('all',
array(
"joins" => $joins,
"fields" => array(.........) // Specify all your desired fields here
"conditions" => array(....) // Specify all conditions for Project, ProjectFunderName models.
)
);
Hope this helps.
Peace! xD

drupal form field not loading correct data

I am building my first Drupal 7 module and am having trouble with the screen to edit a fieldable entity. I am using field_attach_form and it is working great for all accept one field which is displaying the field default rather than the current content of that field for that entity.
I have a text field, a number field, a number of Boolean fields and the one list_text field which is failing.
Any ideas what I a doing incorrectly? Code below is what I think is needed but please do let me know if you need more.
Code to create the field in hook_enable:
if (!field_info_field('field_available')) {
$field = array (
'field_name' => 'field_available',
'type' => 'list_text',
'settings' => array(
'allowed_values' => array('No', 'Provisionally', 'Yes'),
),
);
field_create_field($field);
Code to create the instance, also in hook_enable:
if (!field_info_instance('appointments_status', 'field_available', 'appointments_status')) {
$instance = array(
'field_name' => 'field_available',
'entity_type' => 'appointments_status',
'bundle' => 'appointments_status',
'label' => t('Available?'),
'required' => TRUE,
'default_value' => array(array('value' => 'No')),
'description' => t('Set to No if appointments with this status make this slot unavailable, Provisionally means that it will only reserve a space temporarily'),
);
field_create_instance($instance);
This entity has only the one bundle with the same name as the entity.
The code to create the URL in hook_menu:
$items['admin/appointments/appointments_statii/%/edit'] = array(
'title' => 'Edit appointment status',
'description' => 'Edit the parameters of the selected status code',
'page callback' => 'drupal_get_form',
'page arguments' => array('appointments_status_edit_form',3),
'access arguments' => array('access administration pages'),
'type' => MENU_CALLBACK,
);
The form function is:
function appointments_status_edit_form($form, &$form_state) {
// Get the status id from the form_state args
$status_id = $form_state['build_info']['args'][0];
// Load the chosen status entity
$status = entity_load_single('appointments_status', $status_id);
// Set up the fields for the form
field_attach_form('appointments_status', $status, $form, $form_state);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Save changes',
'#weight' => 99,
);
return $form;
}
I have used the Devel module's dpm to check that the data is loaded correctly by entity_load_single and it is.
Thanks
Rory
I have answered my own question!
I was also programmatically loading some entities and was not loading this field with the numbers that a list_text field stores, instead I was loading the visual text.
I used a metadata wrapper and the code looked like this:
$w_appointments_status->$appointments_availability= 'Yes';
I changed it to:
$w_appointments_status->$appointments_availability = 2;
In this example 'Yes' was the third allowed value - hence 2.
So the code in my question was in fact correct although I have since added 'widget' and 'formatter' parameters to the instance.
I am sorry if this got some of you scratching your heads thinking ' but that code is correct'!!
Regards
Rory

How to find in joining tables Cakephp?

Well this is the problem. I have a table 'Store' that is join to a table 'Product', so each Store (for example Wal-Mart) has a series of products: (coffee, milk, ketchup, etc.) I need to do a find that retrieves only 2 random Stores, with a condition that those Stores must have at least one product.
I am doing the Find like this:
$this->Store->find('all', array( 'conditions' => ...... , 'order' => 'rand()','limit' => 2));
But this find can retrieve a Store with no products.
I can't do the find in the table Product, because multiples products have the same Store and the random can result in the same Store twice.
Do the find in the Products table like you mentioned, and then filter to only get DISTINCT store_id's. This will filter out getting the same store twice. Something similar to:
$this->Store->Product->find('all', array(
'order' => 'rand()',
'limit' => 2,
'fields' => array('DISTINCT(Store.id)')
));
Or just Group By Store.id:
$this->Store->Product->find('all', array(
'order' => 'rand()',
'limit' => 2,
'group' => 'Store.id'
));

Pagination issue when search result

I have 2 Model Playlist and PlaylistTrack PlalistTrack model contains track of playlist. One playlist has many tracks.
Table: Playlist(id,name)
Table: PlaylistTrack(id,track_id,playlist_id)
Following my code.
$conditions=array();
if(isset($this->params->query['search']) && $this->params->query['search']!="")
{
$conditions['AND']['Playlist.name LIKE']="%".$this->params->query['search']."%";
}
$this->paginate = array(
'fields'=>array('Playlist.*','count(`PlaylistTrack`.`track_id`) as tracks'),
'group' => "Playlist.id",
'limit' => 10,
'conditions'=>$condtions,
'joins'=>array(
array(
'table' => 'playlist_tracks',
'alias' => 'PlaylistTrack',
'type' => 'LEFT',
'conditions' => array(
'Playlist.id=PlaylistTrack.playlist_id'
)
)
)
);
$data = $this->paginate('Playlist');
For all record pagination will work fine but when I search from playlist by playlist_name then Display one record with search parameter but there There are two page for one record.
If any further code required just tell me I explain in detail.

Resources