Home › Forums › Backend Issues (wp-admin) › control post order with options page › Reply To: control post order with options page
I do this for posts_per_page for different post types so that clients can determine how many posts to show on archive pages.
You need to create a pre_get_posts query and check settings and alter the query based on the settings.
Here is an example filter I created for a recent project that does this
function pre_get_posts_locations($query) {
// not in admin or if not main query
if (is_admin() || !$query->is_main_query()) {
return;
}
// only queries for location post type
if (!isset($query->query_vars) ||
!isset($query->query_vars['post_type']) ||
$query->query_vars['post_type'] != 'location') {
return;
}
// not for single
if (is_single()) {
return;
}
// set locations per page
$posts_per_page = get_field('locations_per_page', 'options');
if ($posts_per_page === NULL || $posts_per_page === false) {
// if never set show default of 10
$posts_per_page = 10;
}
if (!$posts_per_page) {
// if set to 0 show all
$posts_per_page = -1;
}
$query->set('posts_per_page', $posts_per_page);
// show only active locations
$meta_query = array(
array(
'key' => 'active',
'value' => 1
)
);
$query->set('meta_query', $meta_query);
$orderby = array(
'menu_order' => 'ASC',
'title' => 'ASC'
);
$query->set('orderby', $orderby);
}
The orderby part of the query at the end could also be set up to use options settings if needed.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.