The other day I got a chance to rewrite a bit of code. It was fun. It dealt with changing from an object to an associative array. It may sound super easy for some but for my mind it took a little bit to figure out the right way of creating a good way of filtering that out.
The issue was creating a good way to not only create a layout array with information but a decent way of a theme or plugin to filter it out. Creating some defaults was the easy part. I knew wp_parse_args
would be a good solution to filling in any missing information. So I quickly began with what information was actually needed:
$defaults = apply_filters( 'jmc_layout_args', array( 'layout_name' => '', 'layout_label' => '', 'image_src' => '%s', 'is_global_layout' => false, 'is_post_layout' => true, );
Worked great for setting the main defaults. The next part was making sure the needed layout was filterable. Of course I had to use a foreach
loop to iterate over that.
foreach ( $layouts as $id => $info ) { $layouts[ $id ] = wp_parse_args( $info, $defaults ); }
Cool. I managed to get the layout with some default information if nothing was passed. Well, what happens if you wanted to edit a particular layout’s data? I looked a little closer and realized I could pass one more argument to apply_filters
. Yep!
foreach ( $layouts as $id => $info ) { $defaults = apply_filters( 'jmc_layout_args', array( 'layout_name' => '', 'layout_label' => '', 'image_src' => '%s', 'is_global_layout' => false, 'is_post_layout' => true, ), $id ); $layouts[ $id ] = wp_parse_args( $info, $defaults ); }
Awesome! And with that we can now filter out not only the default arguments passed but on a layout basis if wanted by a theme or plugin.
Let’s say we have three layouts and wanted to change one. We would use something like:
add_filter( 'jmc_layout_args', function( $args, $id ) { if ( $id == 'three column' ) { return array( 'is_global_layout' => true, 'is_post_layout' => false, ); } return $args; }, 10, 2 );
Quick, simple, and a little dirty.