Bootstrap is pretty handy javascript and css library/layer over jquery which provides many useful pre-built functionalities like responsive design, transitions, modals, buttons, etc. In case you want to include twitter bootstrap in a wordpress blog, you may want to include minimum these files:
- bootstrap.css
- bootstrap-responsive.css
- bootstrap.js (or alternatively you can include specific components like bootstrap-button.js, etc.)
To use bootstrap in wordpress for only specific posts (to keep html of other posts light), one approach is to use a custom variable and enqueue bootstrap css and js if that custom variable is set. Here are the steps to achieve this:
- Create a new plugin
wp-bootstrap-control-include
withwp-bootstrap-control-include.php
file andjs
andcss
folders containing bootstrap files. The plugin enqueues appropriate scripts and css based on custom variablewp-bootstrap-include
(or any other variable you prefer). Here is how the code looks like for this:<?php function wbci_enqueue_js_css () { global $post; $post_bootstrap_include_value = get_post_meta($post->ID, 'wp-bootstrap-include', true); if (in_array($post_bootstrap_include_value, array('true', 'on', 'yes')) ) { wp_register_style( 'css/bootstrap-css', plugins_url('bootstrap.css', __FILE__) ); wp_register_style( 'css/bootstrap-responsive-css', plugins_url('bootstrap-responsive.css', __FILE__) ); wp_enqueue_style('bootstrap-css'); wp_enqueue_style('bootstrap-responsive-css'); wp_enqueue_script('bootstrap-js', plugins_url('js/bootstrap.js', __FILE__), array('jquery'), null, true); } } add_action('wp_enqueue_scripts', 'wbci_enqueue_js_css'); ?>
Note that we have included jquery as dependency for bootstrap.js which makes sure that jquery get included before bootstrap.js. - Install the plugin and activate it.
- Set wp-bootstrap-include to true for the desired wordpress post as shown below:
- To test include the following button toggle code (or any other bootstrap code) in a post which has
wp-bootstrap-include
set to true.
<button type="button" class="btn btn-primary" data-toggle="button">Single Toggle</button>
Here is the outcome for the above code:- Button (normal state)
- Button (pressed state)
- Button (normal state)
Few points to note
- I have not included bootstrap icons in this article. But you can easily add support for those by including icon files in img directory in the wordpress plugin.
- You can also access a working version of the wp-bootstrap-control-include plugin on github. The plugin has bare minimum functionalities and you may want to add more stuff to it.