Don’t bother with the checkbox and metabox, that’s limiting:
- You’re only able to have a single slider, and have to add code for every new slider to add a new checkbox
- Data gets stored in post meta as a custom field, but querying posts by their post meta is super expensive and slow
So I present, an alternative that’s much, much easier to implement, and far more flexible:
Use a non-hierarchical Slider Taxonomy
This gives you:
- free archives should you want to expand on your sliders ( optional ofcourse )
- A free UI
- Querying posts for the slider is now super super fast. This is faster than a checkbox in a metabox by orders of magnitude
- The queries scale up as traffic increases and post counts increase. Post meta queries don’t scale
- A free user interface in the form of a checkbox list ( so it’s technically a metabox with a checkbox, funny how that turns out! )
- A slider management UI, under posts you’ll get a page where you can see all your sliders, name them, add descriptions, see how many posts they have, delete/add
- Slider meta! Now you have
slider
terms, you can add term meta! A term meta for transition style? Transition speed? So many possibilities - Posts can now appear in multiple sliders
For example this post appears in a slider named homepage
, no prizes for where that slider might appear:
A post can even appear in multiple sliders!
How Do I setup The Taxonomy?
You would call register_taxonomy
on the init
action, like this:
add_action( 'init', 'create_morteza_slider_tax' );
function create_morteza_slider_tax() {
register_taxonomy(
'morteza_slider',
'post',
array(
'label' => __( 'Sliders' ),
'hierarchical' => false,
'public' => false
)
);
}
How Do I fetch the posts for my slider?
You use the taxonomy name as a parameter in the post query:
$query = new WP_Query( [
'morteza_slider' => 'homepage' // <-- this is all that's needed
] );
Then follow it up with a standard post loop:
// a standard post loop
if ( $query->have_posts() ) {
echo 'start slider markup';
while ( $query->have_posts() ) {
$query->the_post();
// TODO: output this post as a slide
}
wp_reset_postdata();
echo 'end slider markup';
}
Making sure to swap out the various bits, e.g. the “start slider markup” gets replaced with whatever your slider library requires to work