Sort Custom Post Type Archive with Plugin
-
I have a custom post type that I want to be able to sort by a custom field in a plugin, rather than the theme’s functions.php file.
Here is my function:
//Sort CPT By Custom Field function sort_archive_loop($query) { if (!is_admin() && $query->is_post_type_archive('my-cpt') && $query->is_main_query()) { $query->set('meta_key', 'custom-field'); $query->set('order', 'ASC'); $query->set('orderby', 'meta_value'); } } add_action('pre_get_posts', 'sort_archive_loop');
When I put this function in functions.php, it works as expected by sorting the custom post type (my-cpt) archive page by the custom field (custom-field) in ascending order. When I take it out of functions.php and put it in a plugin, it doesn’t change the sort order at all.
Does the function have to be different because it is being called from a plugin? I haven’t found any documentation on this saying it was different, but maybe I missed something.
The plugin is activated.
I’m trying to use the plugin approach over the theme’s functions.php approach as I am building this for someone who may eventually take over the site on their own. I don’t want them to lose the sorted custom post type if they were to change the site theme somewhere down the line.
- The topic ‘Sort Custom Post Type Archive with Plugin’ is closed to new replies.