Last night I submitted WP File Hide to WordPress.org. It felt great, second plugin in review. I’ve got my third plugin, WP Name Your Donation, functional and now I just need to clean it up, comment better and submit.
I’ve been pushing hard to become a better WordPress dev. I’ve been forcing myself to do any task the right way even if there is a shortcut that will work just fine (in a small app). For instance including js in a plugin. In WP Name Your Donation one of the gateway options is Stripe. Stripe requires you to include a public api key in javascript. This is a key that I allow the site owner to set in their admin settings. I did some research and realized I had two options.
1) Echo out the javascript in a php function then add it to a hook. From what I could tell, this was the sloppy and easy way. Funnily, this was the first tutorial I found and it was on a WordPress codex page. Same page had the below method as well underneath this first one.
2) Register a .js file and localize it allowing variables to be passed. This seemed a bit more complicated but I opted to go that route after screwing around with option 1 and feeling the sloppiness build up. Final code came out like this:
stripe.php
wp_register_script( 'key', plugin_dir_url( __FILE__ ) . '../../gateways/stripe/key.js', array( 'jquery' ), '1.0', true );
$pubkey = array();
if( isset( $options['wpnyd_stripe-mode'] ) && isset( $options['wpnyd_stripe-tpk'] ) ) {
$pubkey['pubkey'] = trim( esc_attr( $options['wpnyd_stripe-tpk'] ) );
} elseif( isset( $options['wpnyd_stripe-lpk'] ) ) {
$pubkey['pubkey'] = trim( esc_attr( $options['wpnyd_stripe-lpk' ] ) );
}
wp_localize_script( 'key', 'pubkey', $pubkey );
wp_enqueue_script( 'key' );
key.js
Stripe.setPublishableKey(pubkey.pubkey);