Misc notes for WordPress

Proper way to add js variables from php is to use localize script.

An efficient way of doing it:

First register the script at the beginning (main.js as an example).

Then if any variables need to be added from php to js you create a call back for a custom filter:

That will add a js variable admin_ajax_url when the script is finally included. The nonce or any other data could be added as well.

Finally, we check the filter to see if any data has been added to it and if not we do not localize the script:

Body and Post Class

WordPress provides body_class() and post_class() which will provide useful classes on both <body> and the individual post i.e. <article> that will give information to target things like specific post ids etc. The functions are to be used like :

 

in_the_loop()

Useful for determining if the caller is within the loop. So for example, if you added an action to ‘loop_end’ to display something after the last of the loop using a condition with in_the_loop() it will make sure the contents of the action will only execute  if it is within the main posts loop.

Including CSS/Javascript for a shortcode

As long as the styles/scripts are registered.. they can be actually en-queued within the actual short code code so that the script/styles will only actually load when the short code is used.

Conditionally enqueueing scripts/styles in admin area

When adding an action to ‘admin_enqueue_scripts’ to enqueue scripts, $hook is passed in to determine what page in the admin area you are on.

To test if you are on a certain plugin menu page you can create a global variable to check against the $hook.

Example:

 

To help with removing render-blocking resources from javascript files:

 

Rewrite API and when/how to flush_rewrite_rules

The simplest solution is to delete the option that WordPress sets after building the rewrite rules upon the plugins activation and deactivation hooks. This will force WordPress to rebuild the rules that you may have added.

 

Change the placeholder for Add Title field on custom post type:

Custom Excerpt