Category: Code

Properly Add Styles and Scripts in WordPress

Properly Add Styles and Scripts in WordPress

At first, you should know the following hooks and functions.

Hooks

  • wp_enqueue_scripts: is the proper hook to use when enqueuing items that are meant to appear on the front end. Despite the name, it is used for enqueuing both scripts and styles.
  • wp_head: is triggered within thesection of the users template by the wp_head() function.
  • wp_footer: is triggered near the tag of the users template by the wp_footer() function.

Functions

  • wp_enqueue_style: A safe way to add/enqueue a CSS style file to the wordpress generated page.
  • wp_enqueue_script: Links a script file to the generated page at the right time according to the script dependencies
  • wp_add_inline_style: Works only if the stylesheet has already been added.

Example:

Only Show Posts that Has Featured Image

Only Show Posts that Has Featured Image

Lets query the 6 recent posts simply, use class WP_Query to create a new posts query:

It works well. But sometimes I only want to show the posts that has been set featured image. It is very easy to implement. Set meta_key parameter to WP_Query, See:

It will only display the posts that has featured image.
If you only want to show posts that has featured image in home, use pre_get_posts hook, see:

Or only in category, function wphigh_featured_image_posts() change to:

Only in specific category ID: