More reliable feature adding
-
Hi,
I’ve checked your plugin’s source code, it’s quite fine, nothing heavy – I like that! ;-),
but there is one thing that seems a bit unreliable for future: You are recreating the buttons array by hardcoding all the button IDs to it. This has only 1 advantage and that is “performance”, I use quotes, because nowadays future-proofing this would be a better way.So may I suggest a better solution? In filter callback, create new array and go through the current array, if you hit the button you’re looking for, act accordingly, optionaly, you can store a boolean whether or not you’ve found the proper place and if not – put it e.g. at the end of the re-created array.
The point of this is mainly that if WordPress (or actually anybody else e.g. other plugin) adds some new button before your filter is applied – the button would be removed with your current solution.
Let me share the code that demonstrates such button handling:
Probably more readable code link: https://ideone.com/pf3osEadd_filter( 'mce_buttons', function( $originalButtonsInFirstRow ){ $buttonsToAdd = [ //'new_button_ID_to_add' => 'put_it_after_button_ID', 'alignjustify' => 'alignright', //add justify after align right 'underline' => 'italic', //add underline after italic ]; $newButtonsInFirstRow = []; foreach( $originalButtonsInFirstRow as $buttonID ){ $newButtonsInFirstRow[] = $buttonID; //re-push originals to keep them intact foreach( $buttonsToAdd as $newButtonID => $putItAfterButtonID ){ //Firstly, chack whether the button was already added by us or not! (...!==true) if( ($putItAfterButtonID !== true) && ($buttonID == $putItAfterButtonID) ){ $newButtonsInFirstRow[] = $newButtonID; $buttonsToAdd[$newButtonID] = true; //make a note that button was added } } } //Now check, if all buttons where actually added (in case "put_it_after_button_ID" was missing...) foreach( $buttonsToAdd as $newButtonID => $putItAfterButtonID ){ // check if the button was added (note the type check !== (negated ===)) //if the button wasn't added, put it at the and of the buttons array if( $putItAfterButtonID !== true ) $newButtonsInFirstRow[] = $newButtonID; } return $newButtonsInFirstRow; }, 5 );
Thank you for considering this approach and making WordPress great ! ??
- The topic ‘More reliable feature adding’ is closed to new replies.