Rename inc/ to lib/

This commit is contained in:
Ben Word
2012-08-20 19:19:39 -05:00
parent 9801e69b3b
commit 5c777f361b
13 changed files with 11 additions and 11 deletions

31
lib/actions.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
/**
* Add the RSS feed link in the <head> if there's posts
*/
function roots_feed_link() {
$count = wp_count_posts('post'); if ($count->publish > 0) {
echo "\n\t<link rel=\"alternate\" type=\"application/rss+xml\" title=\"". get_bloginfo('name') ." Feed\" href=\"". home_url() ."/feed/\">\n";
}
}
add_action('wp_head', 'roots_feed_link', -2);
/**
* Add the asynchronous Google Analytics snippet from HTML5 Boilerplate
* if an ID is defined in config.php
*
* @link mathiasbynens.be/notes/async-analytics-snippet
*/
function roots_google_analytics() {
if (GOOGLE_ANALYTICS_ID) {
echo "\n\t<script>\n";
echo "\t\tvar _gaq=[['_setAccount','" . GOOGLE_ANALYTICS_ID . "'],['_trackPageview']];\n";
echo "\t\t(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];\n";
echo "\t\tg.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';\n";
echo "\t\ts.parentNode.insertBefore(g,s)}(document,'script'));\n";
echo "\t</script>\n";
}
}
add_action('wp_footer', 'roots_google_analytics');

324
lib/activation.php Normal file
View File

@@ -0,0 +1,324 @@
<?php
if (is_admin() && isset($_GET['activated']) && 'themes.php' == $GLOBALS['pagenow']) {
wp_redirect(admin_url('themes.php?page=theme_activation_options'));
exit;
}
function roots_theme_activation_options_init() {
if (roots_get_theme_activation_options() === false) {
add_option('roots_theme_activation_options', roots_get_default_theme_activation_options());
}
register_setting(
'roots_activation_options',
'roots_theme_activation_options',
'roots_theme_activation_options_validate'
);
}
add_action('admin_init', 'roots_theme_activation_options_init');
function roots_activation_options_page_capability($capability) {
return 'edit_theme_options';
}
add_filter('option_page_capability_roots_activation_options', 'roots_activation_options_page_capability');
function roots_theme_activation_options_add_page() {
$roots_activation_options = roots_get_theme_activation_options();
if (!$roots_activation_options['first_run']) {
$theme_page = add_theme_page(
__('Theme Activation', 'roots'),
__('Theme Activation', 'roots'),
'edit_theme_options',
'theme_activation_options',
'roots_theme_activation_options_render_page'
);
} else {
if (is_admin() && isset($_GET['page']) && $_GET['page'] === 'theme_activation_options') {
global $wp_rewrite;
$wp_rewrite->flush_rules();
wp_redirect(admin_url('themes.php'));
exit;
}
}
}
add_action('admin_menu', 'roots_theme_activation_options_add_page', 50);
function roots_get_default_theme_activation_options() {
$default_theme_activation_options = array(
'first_run' => false,
'create_front_page' => false,
'change_permalink_structure' => false,
'change_uploads_folder' => false,
'create_navigation_menus' => false,
'add_pages_to_primary_navigation' => false,
);
return apply_filters('roots_default_theme_activation_options', $default_theme_activation_options);
}
function roots_get_theme_activation_options() {
return get_option('roots_theme_activation_options', roots_get_default_theme_activation_options());
}
function roots_theme_activation_options_render_page() { ?>
<div class="wrap">
<?php screen_icon(); ?>
<h2><?php printf(__('%s Theme Activation', 'roots'), wp_get_theme() ); ?></h2>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields('roots_activation_options');
$roots_activation_options = roots_get_theme_activation_options();
$roots_default_activation_options = roots_get_default_theme_activation_options();
?>
<input type="hidden" value="1" name="roots_theme_activation_options[first_run]" />
<table class="form-table">
<tr valign="top"><th scope="row"><?php _e('Create static front page?', 'roots'); ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e('Create static front page?', 'roots'); ?></span></legend>
<select name="roots_theme_activation_options[create_front_page]" id="create_front_page">
<option selected="selected" value="yes"><?php echo _e('Yes', 'roots'); ?></option>
<option value="no"><?php echo _e('No', 'roots'); ?></option>
</select>
<br />
<small class="description"><?php printf(__('Create a page called Home and set it to be the static front page', 'roots')); ?></small>
</fieldset>
</td>
</tr>
<tr valign="top"><th scope="row"><?php _e('Change permalink structure?', 'roots'); ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e('Update permalink structure?', 'roots'); ?></span></legend>
<select name="roots_theme_activation_options[change_permalink_structure]" id="change_permalink_structure">
<option selected="selected" value="yes"><?php echo _e('Yes', 'roots'); ?></option>
<option value="no"><?php echo _e('No', 'roots'); ?></option>
</select>
<br />
<small class="description"><?php printf(__('Change permalink structure to /&#37;postname&#37;/', 'roots')); ?></small>
</fieldset>
</td>
</tr>
<tr valign="top"><th scope="row"><?php _e('Change uploads folder?', 'roots'); ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e('Update uploads folder?', 'roots'); ?></span></legend>
<select name="roots_theme_activation_options[change_uploads_folder]" id="change_uploads_folder">
<option selected="selected" value="yes"><?php echo _e('Yes', 'roots'); ?></option>
<option value="no"><?php echo _e('No', 'roots'); ?></option>
</select>
<br />
<small class="description"><?php printf(__('Change uploads folder to /assets/ instead of /wp-content/uploads/', 'roots')); ?></small>
</fieldset>
</td>
</tr>
<tr valign="top"><th scope="row"><?php _e('Create navigation menu?', 'roots'); ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e('Create navigation menu?', 'roots'); ?></span></legend>
<select name="roots_theme_activation_options[create_navigation_menus]" id="create_navigation_menus">
<option selected="selected" value="yes"><?php echo _e('Yes', 'roots'); ?></option>
<option value="no"><?php echo _e('No', 'roots'); ?></option>
</select>
<br />
<small class="description"><?php printf(__('Create the Primary Navigation menu and set the location', 'roots')); ?></small>
</fieldset>
</td>
</tr>
<tr valign="top"><th scope="row"><?php _e('Add pages to menu?', 'roots'); ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e('Add pages to menu?', 'roots'); ?></span></legend>
<select name="roots_theme_activation_options[add_pages_to_primary_navigation]" id="add_pages_to_primary_navigation">
<option selected="selected" value="yes"><?php echo _e('Yes', 'roots'); ?></option>
<option value="no"><?php echo _e('No', 'roots'); ?></option>
</select>
<br />
<small class="description"><?php printf(__('Add all current published pages to the Primary Navigation', 'roots')); ?></small>
</fieldset>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php }
function roots_theme_activation_options_validate($input) {
$output = $defaults = roots_get_default_theme_activation_options();
if (isset($input['first_run'])) {
if ($input['first_run'] === '1') {
$input['first_run'] = true;
}
$output['first_run'] = $input['first_run'];
}
if (isset($input['create_front_page'])) {
if ($input['create_front_page'] === 'yes') {
$input['create_front_page'] = true;
}
if ($input['create_front_page'] === 'no') {
$input['create_front_page'] = false;
}
$output['create_front_page'] = $input['create_front_page'];
}
if (isset($input['change_permalink_structure'])) {
if ($input['change_permalink_structure'] === 'yes') {
$input['change_permalink_structure'] = true;
}
if ($input['change_permalink_structure'] === 'no') {
$input['change_permalink_structure'] = false;
}
$output['change_permalink_structure'] = $input['change_permalink_structure'];
}
if (isset($input['change_uploads_folder'])) {
if ($input['change_uploads_folder'] === 'yes') {
$input['change_uploads_folder'] = true;
}
if ($input['change_uploads_folder'] === 'no') {
$input['change_uploads_folder'] = false;
}
$output['change_uploads_folder'] = $input['change_uploads_folder'];
}
if (isset($input['create_navigation_menus'])) {
if ($input['create_navigation_menus'] === 'yes') {
$input['create_navigation_menus'] = true;
}
if ($input['create_navigation_menus'] === 'no') {
$input['create_navigation_menus'] = false;
}
$output['create_navigation_menus'] = $input['create_navigation_menus'];
}
if (isset($input['add_pages_to_primary_navigation'])) {
if ($input['add_pages_to_primary_navigation'] === 'yes') {
$input['add_pages_to_primary_navigation'] = true;
}
if ($input['add_pages_to_primary_navigation'] === 'no') {
$input['add_pages_to_primary_navigation'] = false;
}
$output['add_pages_to_primary_navigation'] = $input['add_pages_to_primary_navigation'];
}
return apply_filters('roots_theme_activation_options_validate', $output, $input, $defaults);
}
function roots_theme_activation_action() {
$roots_theme_activation_options = roots_get_theme_activation_options();
if ($roots_theme_activation_options['create_front_page']) {
$roots_theme_activation_options['create_front_page'] = false;
$default_pages = array('Home');
$existing_pages = get_pages();
$temp = array();
foreach ($existing_pages as $page) {
$temp[] = $page->post_title;
}
$pages_to_create = array_diff($default_pages, $temp);
foreach ($pages_to_create as $new_page_title) {
$add_default_pages = array(
'post_title' => $new_page_title,
'post_content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum consequat, orci ac laoreet cursus, dolor sem luctus lorem, eget consequat magna felis a magna. Aliquam scelerisque condimentum ante, eget facilisis tortor lobortis in. In interdum venenatis justo eget consequat. Morbi commodo rhoncus mi nec pharetra. Aliquam erat volutpat. Mauris non lorem eu dolor hendrerit dapibus. Mauris mollis nisl quis sapien posuere consectetur. Nullam in sapien at nisi ornare bibendum at ut lectus. Pellentesque ut magna mauris. Nam viverra suscipit ligula, sed accumsan enim placerat nec. Cras vitae metus vel dolor ultrices sagittis. Duis venenatis augue sed risus laoreet congue ac ac leo. Donec fermentum accumsan libero sit amet iaculis. Duis tristique dictum enim, ac fringilla risus bibendum in. Nunc ornare, quam sit amet ultricies gravida, tortor mi malesuada urna, quis commodo dui nibh in lacus. Nunc vel tortor mi. Pellentesque vel urna a arcu adipiscing imperdiet vitae sit amet neque. Integer eu lectus et nunc dictum sagittis. Curabitur commodo vulputate fringilla. Sed eleifend, arcu convallis adipiscing congue, dui turpis commodo magna, et vehicula sapien turpis sit amet nisi.',
'post_status' => 'publish',
'post_type' => 'page'
);
$result = wp_insert_post($add_default_pages);
}
$home = get_page_by_title('Home');
update_option('show_on_front', 'page');
update_option('page_on_front', $home->ID);
$home_menu_order = array(
'ID' => $home->ID,
'menu_order' => -1
);
wp_update_post($home_menu_order);
}
if ($roots_theme_activation_options['change_permalink_structure']) {
$roots_theme_activation_options['change_permalink_structure'] = false;
if (get_option('permalink_structure') !== '/%postname%/') {
update_option('permalink_structure', '/%postname%/');
}
global $wp_rewrite;
$wp_rewrite->init();
$wp_rewrite->flush_rules();
}
if ($roots_theme_activation_options['change_uploads_folder']) {
$roots_theme_activation_options['change_uploads_folder'] = false;
update_option('uploads_use_yearmonth_folders', 0);
update_option('upload_path', 'assets');
}
if ($roots_theme_activation_options['create_navigation_menus']) {
$roots_theme_activation_options['create_navigation_menus'] = false;
$roots_nav_theme_mod = false;
if (!has_nav_menu('primary_navigation')) {
$primary_nav_id = wp_create_nav_menu('Primary Navigation', array('slug' => 'primary_navigation'));
$roots_nav_theme_mod['primary_navigation'] = $primary_nav_id;
}
if ($roots_nav_theme_mod) {
set_theme_mod('nav_menu_locations', $roots_nav_theme_mod);
}
}
if ($roots_theme_activation_options['add_pages_to_primary_navigation']) {
$roots_theme_activation_options['add_pages_to_primary_navigation'] = false;
$primary_nav = wp_get_nav_menu_object('Primary Navigation');
$primary_nav_term_id = (int) $primary_nav->term_id;
$menu_items= wp_get_nav_menu_items($primary_nav_term_id);
if (!$menu_items || empty($menu_items)) {
$pages = get_pages();
foreach($pages as $page) {
$item = array(
'menu-item-object-id' => $page->ID,
'menu-item-object' => 'page',
'menu-item-type' => 'post_type',
'menu-item-status' => 'publish'
);
wp_update_nav_menu_item($primary_nav_term_id, 0, $item);
}
}
}
update_option('roots_theme_activation_options', $roots_theme_activation_options);
}
add_action('admin_init','roots_theme_activation_action');
function roots_deactivation_action() {
update_option('roots_theme_activation_options', roots_get_default_theme_activation_options());
}
add_action('switch_theme', 'roots_deactivation_action');

676
lib/cleanup.php Normal file
View File

@@ -0,0 +1,676 @@
<?php
/**
* Redirects search results from /?s=query to /search/query/, converts %20 to +
*
* @link http://txfx.net/wordpress-plugins/nice-search/
*/
function roots_nice_search_redirect() {
if (is_search() && strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === false && strpos($_SERVER['REQUEST_URI'], '/search/') === false) {
wp_redirect(home_url('/search/' . str_replace(array(' ', '%20'), array('+', '+'), urlencode(get_query_var('s')))), 301);
exit();
}
}
add_action('template_redirect', 'roots_nice_search_redirect');
/**
* Fix for get_search_query() returning +'s between search terms
*/
function roots_search_query($escaped = true) {
$query = apply_filters('roots_search_query', get_query_var('s'));
if ($escaped) {
$query = esc_attr($query);
}
return urldecode($query);
}
add_filter('get_search_query', 'roots_search_query');
/**
* Fix for empty search queries redirecting to home page
*
* @link http://wordpress.org/support/topic/blank-search-sends-you-to-the-homepage#post-1772565
* @link http://core.trac.wordpress.org/ticket/11330
*/
function roots_request_filter($query_vars) {
if (isset($_GET['s']) && empty($_GET['s'])) {
$query_vars['s'] = ' ';
}
return $query_vars;
}
add_filter('request', 'roots_request_filter');
/**
* Root relative URLs
*
* WordPress likes to use absolute URLs on everything - let's clean that up.
* Inspired by http://www.456bereastreet.com/archive/201010/how_to_make_wordpress_urls_root_relative/
*
* You can enable/disable this feature in config.php:
* current_theme_supports('root-relative-urls');
*
* @author Scott Walkinshaw <scott.walkinshaw@gmail.com>
*/
function roots_root_relative_url($input) {
$output = preg_replace_callback(
'!(https?://[^/|"]+)([^"]+)?!',
create_function(
'$matches',
// If full URL is home_url("/") and this isn't a subdir install, return a slash for relative root
'if (isset($matches[0]) && $matches[0] === home_url("/") && str_replace("http://", "", home_url("/", "http"))==$_SERVER["HTTP_HOST"]) { return "/";' .
// If domain is equal to home_url("/"), then make URL relative
'} elseif (isset($matches[0]) && strpos($matches[0], home_url("/")) !== false) { return $matches[2];' .
// If domain is not equal to home_url("/"), do not make external link relative
'} else { return $matches[0]; };'
),
$input
);
return $output;
}
/**
* Terrible workaround to remove the duplicate subfolder in the src of <script> and <link> tags
* Example: /subfolder/subfolder/css/style.css
*/
function roots_fix_duplicate_subfolder_urls($input) {
$output = roots_root_relative_url($input);
preg_match_all('!([^/]+)/([^/]+)!', $output, $matches);
if (isset($matches[1]) && isset($matches[2])) {
if ($matches[1][0] === $matches[2][0]) {
$output = substr($output, strlen($matches[1][0]) + 1);
}
}
return $output;
}
function enable_root_relative_urls() {
return !(is_admin() && in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'))) && current_theme_supports('root-relative-urls');
}
if (enable_root_relative_urls()) {
$root_rel_filters = array(
'bloginfo_url',
'theme_root_uri',
'stylesheet_directory_uri',
'template_directory_uri',
'plugins_url',
'the_permalink',
'wp_list_pages',
'wp_list_categories',
'wp_nav_menu',
'the_content_more_link',
'the_tags',
'get_pagenum_link',
'get_comment_link',
'month_link',
'day_link',
'year_link',
'tag_link',
'the_author_posts_link'
);
add_filters($root_rel_filters, 'roots_root_relative_url');
add_filter('script_loader_src', 'roots_fix_duplicate_subfolder_urls');
add_filter('style_loader_src', 'roots_fix_duplicate_subfolder_urls');
}
/**
* Cleanup language_attributes() used in <html> tag
*
* Change lang="en-US" to lang="en"
* Remove dir="ltr"
*/
function roots_language_attributes() {
$attributes = array();
$output = '';
if (function_exists('is_rtl')) {
if (is_rtl() == 'rtl') {
$attributes[] = 'dir="rtl"';
}
}
$lang = get_bloginfo('language');
if ($lang && $lang !== 'en-US') {
$attributes[] = "lang=\"$lang\"";
} else {
$attributes[] = 'lang="en"';
}
$output = implode(' ', $attributes);
$output = apply_filters('roots_language_attributes', $output);
return $output;
}
add_filter('language_attributes', 'roots_language_attributes');
/**
* Remove the WordPress version from RSS feeds
*/
function roots_remove_generator() { return; }
add_filter('the_generator', 'roots_remove_generator');
/**
* Cleanup wp_head()
*
* Remove unnecessary <link>'s
* Remove inline CSS used by Recent Comments widget
* Remove inline CSS used by posts with galleries
* Remove self-closing tag and change ''s to "'s on rel_canonical()
*/
function roots_head_cleanup() {
// http://wpengineer.com/1438/wordpress-header/
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
add_action('wp_head', 'roots_remove_recent_comments_style', 1);
add_filter('use_default_gallery_style', '__return_null');
if (!class_exists('WPSEO_Frontend')) {
remove_action('wp_head', 'rel_canonical');
add_action('wp_head', 'roots_rel_canonical');
}
}
function roots_rel_canonical() {
global $wp_the_query;
if (!is_singular()) {
return;
}
if (!$id = $wp_the_query->get_queried_object_id()) {
return;
}
$link = get_permalink($id);
echo "\t<link rel=\"canonical\" href=\"$link\">\n";
}
function roots_remove_recent_comments_style() {
global $wp_widget_factory;
if (isset($wp_widget_factory->widgets['WP_Widget_Recent_Comments'])) {
remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style'));
}
}
add_action('init', 'roots_head_cleanup');
/**
* Cleanup gallery_shortcode()
*
* Re-create the [gallery] shortcode and use thumbnails styling from Bootstrap
*
* @link http://twitter.github.com/bootstrap/components.html#thumbnails
*/
function roots_gallery($attr) {
global $post, $wp_locale;
static $instance = 0;
$instance++;
$output = apply_filters('post_gallery', '', $attr);
if ($output != '') {
return $output;
}
if (isset($attr['orderby'])) {
$attr['orderby'] = sanitize_sql_orderby($attr['orderby']);
if (!$attr['orderby']) {
unset($attr['orderby']);
}
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'icontag' => 'li',
'captiontag' => 'p',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ($order === 'RAND') {
$orderby = 'none';
}
if (!empty($include)) {
$include = preg_replace( '/[^0-9,]+/', '', $include );
$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
$attachments = array();
foreach ($_attachments as $key => $val) {
$attachments[$val->ID] = $_attachments[$key];
}
} elseif (!empty($exclude)) {
$exclude = preg_replace('/[^0-9,]+/', '', $exclude);
$attachments = get_children(array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby));
} else {
$attachments = get_children(array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby));
}
if (empty($attachments)) {
return '';
}
if (is_feed()) {
$output = "\n";
foreach ($attachments as $att_id => $attachment)
$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
return $output;
}
$captiontag = tag_escape($captiontag);
$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';
$selector = "gallery-{$instance}";
$gallery_style = $gallery_div = '';
if (apply_filters('use_default_gallery_style', true)) {
$gallery_style = '';
}
$size_class = sanitize_html_class($size);
$gallery_div = "<ul id='$selector' class='thumbnails gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
$output = apply_filters('gallery_style', $gallery_style . "\n\t\t" . $gallery_div);
$i = 0;
foreach ($attachments as $id => $attachment) {
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
$output .= "
<{$icontag} class=\"gallery-item\">
$link
";
if ($captiontag && trim($attachment->post_excerpt)) {
$output .= "
<{$captiontag} class=\"gallery-caption hidden\">
" . wptexturize($attachment->post_excerpt) . "
</{$captiontag}>";
}
$output .= "</{$icontag}>";
if ($columns > 0 && ++$i % $columns == 0) {
$output .= '';
}
}
$output .= "</ul>\n";
return $output;
}
remove_shortcode('gallery');
add_shortcode('gallery', 'roots_gallery');
/**
* Add class="thumbnail" to attachment items
*/
function roots_attachment_link_class($html) {
$postid = get_the_ID();
$html = str_replace('<a', '<a class="thumbnail"', $html);
return $html;
}
add_filter('wp_get_attachment_link', 'roots_attachment_link_class', 10, 1);
/**
* Add Bootstrap thumbnail styling to images with captions
* Use <figure> and <figcaption>
*
* @link http://justintadlock.com/archives/2011/07/01/captions-in-wordpress
*/
function roots_caption($output, $attr, $content) {
if (is_feed()) {
return $output;
}
$defaults = array(
'id' => '',
'align' => 'alignnone',
'width' => '',
'caption' => ''
);
$attr = shortcode_atts($defaults, $attr);
// If the width is less than 1 or there is no caption, return the content wrapped between the [caption] tags
if (1 > $attr['width'] || empty($attr['caption'])) {
return $content;
}
// Set up the attributes for the caption <div>
$attributes = (!empty($attr['id']) ? ' id="' . esc_attr($attr['id']) . '"' : '' );
$attributes .= ' class="thumbnail wp-caption ' . esc_attr($attr['align']) . '"';
$attributes .= ' style="width: ' . esc_attr($attr['width']) . 'px"';
$output = '<figure' . $attributes .'>';
$output .= do_shortcode($content);
$output .= '<figcaption class="caption wp-caption-text">' . $attr['caption'] . '</figcaption>';
$output .= '</figure>';
return $output;
}
add_filter('img_caption_shortcode', 'roots_caption', 10, 3);
/**
* Remove unnecessary dashboard widgets
*
* @link http://www.deluxeblogtips.com/2011/01/remove-dashboard-widgets-in-wordpress.html
*/
function roots_remove_dashboard_widgets() {
remove_meta_box('dashboard_incoming_links', 'dashboard', 'normal');
remove_meta_box('dashboard_plugins', 'dashboard', 'normal');
remove_meta_box('dashboard_primary', 'dashboard', 'normal');
remove_meta_box('dashboard_secondary', 'dashboard', 'normal');
}
add_action('admin_init', 'roots_remove_dashboard_widgets');
/**
* Cleanup the_excerpt()
*/
function roots_excerpt_length($length) {
return POST_EXCERPT_LENGTH;
}
function roots_excerpt_more($more) {
return ' &hellip; <a href="' . get_permalink() . '">' . __('Continued', 'roots') . '</a>';
}
add_filter('excerpt_length', 'roots_excerpt_length');
add_filter('excerpt_more', 'roots_excerpt_more');
/**
* Replace various active menu class names with "active"
*/
function roots_wp_nav_menu($text) {
$text = preg_replace('/(current(-menu-|[-_]page[-_])(item|parent|ancestor))/', 'active', $text);
$text = preg_replace('/( active){2,}/', ' active', $text);
return $text;
}
add_filter('wp_nav_menu', 'roots_wp_nav_menu');
/**
* Cleaner walker for wp_nav_menu()
*
* Walker_Nav_Menu (WordPress default) example output:
* <li id="menu-item-8" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-8"><a href="/">Home</a></li>
* <li id="menu-item-9" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-9"><a href="/sample-page/">Sample Page</a></l
*
* Roots_Nav_Walker example output:
* <li class="menu-home"><a href="/">Home</a></li>
* <li class="menu-sample-page"><a href="/sample-page/">Sample Page</a></li>
*/
class Roots_Nav_Walker extends Walker_Nav_Menu {
function check_current($classes) {
return preg_match('/(current[-_])|active|dropdown/', $classes);
}
function start_lvl(&$output, $depth = 0, $args = array()) {
$output .= "\n<ul class=\"dropdown-menu\">\n";
}
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
global $wp_query;
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$slug = sanitize_title($item->title);
$id = 'menu-' . $slug;
$class_names = $value = '';
$li_attributes = '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
$classes = array_filter($classes, array(&$this, 'check_current'));
if ($args->has_children) {
$classes[] = 'dropdown';
$li_attributes .= ' data-dropdown="dropdown"';
}
if ($custom_classes = get_post_meta($item->ID, '_menu_item_classes', true)) {
foreach ($custom_classes as $custom_class) {
$classes[] = $custom_class;
}
}
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
$class_names = $class_names ? ' class="' . $id . ' ' . esc_attr($class_names) . '"' : ' class="' . $id . '"';
$output .= $indent . '<li' . $class_names . '>';
$attributes = ! empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) .'"' : '';
$attributes .= ! empty($item->target) ? ' target="' . esc_attr($item->target ) .'"' : '';
$attributes .= ! empty($item->xfn) ? ' rel="' . esc_attr($item->xfn ) .'"' : '';
$attributes .= ! empty($item->url) ? ' href="' . esc_attr($item->url ) .'"' : '';
$attributes .= ($args->has_children) ? ' class="dropdown-toggle" data-toggle="dropdown"' : '';
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$item_output .= ($args->has_children) ? ' <b class="caret"></b>' : '';
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
function display_element($element, &$children_elements, $max_depth, $depth = 0, $args, &$output) {
if (!$element) { return; }
$id_field = $this->db_fields['id'];
if (is_array($args[0])) {
$args[0]['has_children'] = !empty($children_elements[$element->$id_field]);
} elseif (is_object($args[0])) {
$args[0]->has_children = !empty($children_elements[$element->$id_field]);
}
$cb_args = array_merge(array(&$output, $element, $depth), $args);
call_user_func_array(array(&$this, 'start_el'), $cb_args);
$id = $element->$id_field;
if (($max_depth == 0 || $max_depth > $depth+1) && isset($children_elements[$id])) {
foreach ($children_elements[$id] as $child) {
if (!isset($newlevel)) {
$newlevel = true;
$cb_args = array_merge(array(&$output, $depth), $args);
call_user_func_array(array(&$this, 'start_lvl'), $cb_args);
}
$this->display_element($child, $children_elements, $max_depth, $depth + 1, $args, $output);
}
unset($children_elements[$id]);
}
if (isset($newlevel) && $newlevel) {
$cb_args = array_merge(array(&$output, $depth), $args);
call_user_func_array(array(&$this, 'end_lvl'), $cb_args);
}
$cb_args = array_merge(array(&$output, $element, $depth), $args);
call_user_func_array(array(&$this, 'end_el'), $cb_args);
}
}
/**
* Cleanup wp_nav_menu_args
*
* Remove the container
* Use Roots_Nav_Walker() by default
*/
function roots_nav_menu_args($args = '') {
$roots_nav_menu_args['container'] = false;
if (!$args['items_wrap']) {
$roots_nav_menu_args['items_wrap'] = '<ul class="%2$s">%3$s</ul>';
}
if (current_theme_supports('bootstrap-top-navbar')) {
$roots_nav_menu_args['depth'] = 2;
}
if (!$args['walker']) {
$roots_nav_menu_args['walker'] = new Roots_Nav_Walker();
}
return array_merge($args, $roots_nav_menu_args);
}
add_filter('wp_nav_menu_args', 'roots_nav_menu_args');
/**
* Remove unnecessary self-closing tags
*/
function roots_remove_self_closing_tags($input) {
return str_replace(' />', '>', $input);
}
add_filter('get_avatar', 'roots_remove_self_closing_tags'); // <img />
add_filter('comment_id_fields', 'roots_remove_self_closing_tags'); // <input />
add_filter('post_thumbnail_html', 'roots_remove_self_closing_tags'); // <img />
/**
* Don't return the default description in the RSS feed if it hasn't been changed
*/
function roots_remove_default_description($bloginfo) {
$default_tagline = 'Just another WordPress site';
return ($bloginfo === $default_tagline) ? '' : $bloginfo;
}
add_filter('get_bloginfo_rss', 'roots_remove_default_description');
/**
* Allow more tags in TinyMCE including <iframe> and <script>
*/
function roots_change_mce_options($options) {
$ext = 'pre[id|name|class|style],iframe[align|longdesc|name|width|height|frameborder|scrolling|marginheight|marginwidth|src],script[charset|defer|language|src|type]';
if (isset($initArray['extended_valid_elements'])) {
$options['extended_valid_elements'] .= ',' . $ext;
} else {
$options['extended_valid_elements'] = $ext;
}
return $options;
}
add_filter('tiny_mce_before_init', 'roots_change_mce_options');
/**
* Cleanup output of stylesheet <link> tags
*/
add_filter('style_loader_tag', 'roots_clean_style_tag');
function roots_clean_style_tag($input) {
preg_match_all("!<link rel='stylesheet'\s?(id='[^']+')?\s+href='(.*)' type='text/css' media='(.*)' />!", $input, $matches);
// Only display media if it's print
$media = $matches[3][0] === 'print' ? ' media="print"' : '';
return '<link rel="stylesheet" href="' . $matches[2][0] . '"' . $media . '>' . "\n";
}
/**
* Apply filters to body_class()
*/
function roots_body_class_filter($classes) {
// Add 'top-navbar' class if using Bootstrap's Navbar
if (current_theme_supports('bootstrap-top-navbar')) {
$classes[] = 'top-navbar';
}
return $classes;
}
add_filter('body_class', 'roots_body_class_filter');
/**
* Add additional classes onto widgets
*
* @link http://wordpress.org/support/topic/how-to-first-and-last-css-classes-for-sidebar-widgets
*/
function roots_widget_first_last_classes($params) {
global $my_widget_num;
$this_id = $params[0]['id'];
$arr_registered_widgets = wp_get_sidebars_widgets();
if (!$my_widget_num) {
$my_widget_num = array();
}
if (!isset($arr_registered_widgets[$this_id]) || !is_array($arr_registered_widgets[$this_id])) {
return $params;
}
if (isset($my_widget_num[$this_id])) {
$my_widget_num[$this_id] ++;
} else {
$my_widget_num[$this_id] = 1;
}
$class = 'class="widget-' . $my_widget_num[$this_id] . ' ';
if ($my_widget_num[$this_id] == 1) {
$class .= 'widget-first ';
} elseif ($my_widget_num[$this_id] == count($arr_registered_widgets[$this_id])) {
$class .= 'widget-last ';
}
$params[0]['before_widget'] = preg_replace('/class=\"/', "$class", $params[0]['before_widget'], 1);
return $params;
}
add_filter('dynamic_sidebar_params', 'roots_widget_first_last_classes');
/**
* Wrap embedded media as suggested by Readability
*
* @link https://gist.github.com/965956
* @link http://www.readability.com/publishers/guidelines#publisher
*/
function roots_embed_wrap($cache, $url, $attr = '', $post_ID = '') {
return '<div class="entry-content-asset">' . $cache . '</div>';
}
add_filter('embed_oembed_html', 'roots_embed_wrap', 10, 4);
add_filter('embed_googlevideo', 'roots_embed_wrap', 10, 2);
/**
* Tell WordPress to use searchform.php from the templates/ directory
*/
function roots_get_search_form() {
locate_template('/templates/searchform.php', true, true);
}
add_filter('get_search_form', 'roots_get_search_form');

44
lib/config.php Normal file
View File

@@ -0,0 +1,44 @@
<?php
/**
* Roots configuration and constants
*/
add_theme_support('root-relative-urls'); // Enable relative URLs
add_theme_support('rewrite-urls'); // Enable URL rewrites
add_theme_support('h5bp-htaccess'); // Enable HTML5 Boilerplate's .htaccess
add_theme_support('bootstrap-top-navbar'); // Enable Bootstrap's fixed navbar
// Define which pages shouldn't have the sidebar
function roots_sidebar() {
if (is_404() || is_page_template('page-custom.php')) {
return false;
} else {
return true;
}
}
// #main CSS classes
function roots_main_class() {
if (roots_sidebar()) {
echo 'span8';
} else {
echo 'span12';
}
}
// #sidebar CSS classes
function roots_sidebar_class() {
echo 'span4';
}
$get_theme_name = explode('/themes/', get_template_directory());
define('GOOGLE_ANALYTICS_ID', ''); // UA-XXXXX-Y
define('POST_EXCERPT_LENGTH', 40);
define('WP_BASE', wp_base_dir());
define('THEME_NAME', next($get_theme_name));
define('RELATIVE_PLUGIN_PATH', str_replace(site_url() . '/', '', plugins_url()));
define('FULL_RELATIVE_PLUGIN_PATH', WP_BASE . '/' . RELATIVE_PLUGIN_PATH);
define('RELATIVE_CONTENT_PATH', str_replace(site_url() . '/', '', content_url()));
define('THEME_PATH', RELATIVE_CONTENT_PATH . '/themes/' . THEME_NAME);
// Set the content width based on the theme's design and stylesheet
if (!isset($content_width)) { $content_width = 940; }

3
lib/custom.php Normal file
View File

@@ -0,0 +1,3 @@
<?php
// Custom functions

585
lib/h5bp-htaccess Normal file
View File

@@ -0,0 +1,585 @@
# BEGIN HTML5 Boilerplate
###
### This contains the HTML5 Boilerplate .htaccess that can be found at:
### github.com/h5bp/html5-boilerplate/blob/master/.htaccess
###
### Added:
### Block access to access to WordPress files that reveal version information.
###
### Commented out by default:
### Expires headers: Use WP Super Cache or W3 Total Cache (unless using the H5BP build script)
### ETag removal: Use WP Super Cache or W3 Total Cache (unless using the H5BP build script)
### Start rewrite engine: Handled by WordPress
### Suppress/force www: Handled by WordPress
### Options -MultiViews: Causes a server 500 error on most shared hosts
### Custom 404 page: Handled by WordPress
###
### Anytime you update this file the .htaccess file in the root of your
### WordPress install is automatically updated with the changes whenever
### the permalinks are flushed or set
###
# ----------------------------------------------------------------------
# Better website experience for IE users
# ----------------------------------------------------------------------
# Force the latest IE version, in various cases when it may fall back to IE7 mode
# github.com/rails/rails/commit/123eb25#commitcomment-118920
# Use ChromeFrame if it's installed for a better experience for the poor IE folk
<IfModule mod_headers.c>
Header set X-UA-Compatible "IE=Edge,chrome=1"
# mod_headers can't match by content-type, but we don't want to send this header on *everything*...
<FilesMatch "\.(js|css|gif|png|jpe?g|pdf|xml|oga|ogg|m4a|ogv|mp4|m4v|webm|svg|svgz|eot|ttf|otf|woff|ico|webp|appcache|manifest|htc|crx|oex|xpi|safariextz|vcf)$" >
Header unset X-UA-Compatible
</FilesMatch>
</IfModule>
# ----------------------------------------------------------------------
# Cross-domain AJAX requests
# ----------------------------------------------------------------------
# Serve cross-domain Ajax requests, disabled by default.
# enable-cors.org
# code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
# <IfModule mod_headers.c>
# Header set Access-Control-Allow-Origin "*"
# </IfModule>
# ----------------------------------------------------------------------
# CORS-enabled images (@crossorigin)
# ----------------------------------------------------------------------
# Send CORS headers if browsers request them; enabled by default for images.
# developer.mozilla.org/en/CORS_Enabled_Image
# blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html
# hacks.mozilla.org/2011/11/using-cors-to-load-webgl-textures-from-cross-domain-images/
# wiki.mozilla.org/Security/Reviews/crossoriginAttribute
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
# mod_headers, y u no match by Content-Type?!
<FilesMatch "\.(gif|png|jpe?g|svg|svgz|ico|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
# ----------------------------------------------------------------------
# Webfont access
# ----------------------------------------------------------------------
# Allow access from all domains for webfonts.
# Alternatively you could only whitelist your
# subdomains like "subdomain.example.com".
<IfModule mod_headers.c>
<FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
# ----------------------------------------------------------------------
# Proper MIME type for all files
# ----------------------------------------------------------------------
# JavaScript
# Normalize to standard type (it's sniffed in IE anyways)
# tools.ietf.org/html/rfc4329#section-7.2
AddType application/javascript js jsonp
AddType application/json json
# Audio
AddType audio/ogg oga ogg
AddType audio/mp4 m4a f4a f4b
# Video
AddType video/ogg ogv
AddType video/mp4 mp4 m4v f4v f4p
AddType video/webm webm
AddType video/x-flv flv
# SVG
# Required for svg webfonts on iPad
# twitter.com/FontSquirrel/status/14855840545
AddType image/svg+xml svg svgz
AddEncoding gzip svgz
# Webfonts
AddType application/vnd.ms-fontobject eot
AddType application/x-font-ttf ttf ttc
AddType font/opentype otf
AddType application/x-font-woff woff
# Assorted types
AddType image/x-icon ico
AddType image/webp webp
AddType text/cache-manifest appcache manifest
AddType text/x-component htc
AddType application/xml rss atom xml rdf
AddType application/x-chrome-extension crx
AddType application/x-opera-extension oex
AddType application/x-xpinstall xpi
AddType application/octet-stream safariextz
AddType application/x-web-app-manifest+json webapp
AddType text/x-vcard vcf
AddType application/x-shockwave-flash swf
# ----------------------------------------------------------------------
# Allow concatenation from within specific js and css files
# ----------------------------------------------------------------------
# e.g. Inside of script.combined.js you could have
# <!--#include file="libs/jquery-1.5.0.min.js" -->
# <!--#include file="plugins/jquery.idletimer.js" -->
# and they would be included into this single file.
# This is not in use in the boilerplate as it stands. You may
# choose to name your files in this way for this advantage or
# concatenate and minify them manually.
# Disabled by default.
#<FilesMatch "\.combined\.js$">
# Options +Includes
# AddOutputFilterByType INCLUDES application/javascript application/json
# SetOutputFilter INCLUDES
#</FilesMatch>
#<FilesMatch "\.combined\.css$">
# Options +Includes
# AddOutputFilterByType INCLUDES text/css
# SetOutputFilter INCLUDES
#</FilesMatch>
# ----------------------------------------------------------------------
# Gzip compression
# ----------------------------------------------------------------------
<IfModule mod_deflate.c>
# Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
</IfModule>
</IfModule>
# HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
<IfModule filter_module>
FilterDeclare COMPRESS
FilterProvider COMPRESS DEFLATE resp=Content-Type $text/html
FilterProvider COMPRESS DEFLATE resp=Content-Type $text/css
FilterProvider COMPRESS DEFLATE resp=Content-Type $text/plain
FilterProvider COMPRESS DEFLATE resp=Content-Type $text/xml
FilterProvider COMPRESS DEFLATE resp=Content-Type $text/x-component
FilterProvider COMPRESS DEFLATE resp=Content-Type $application/javascript
FilterProvider COMPRESS DEFLATE resp=Content-Type $application/json
FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xml
FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xhtml+xml
FilterProvider COMPRESS DEFLATE resp=Content-Type $application/rss+xml
FilterProvider COMPRESS DEFLATE resp=Content-Type $application/atom+xml
FilterProvider COMPRESS DEFLATE resp=Content-Type $application/vnd.ms-fontobject
FilterProvider COMPRESS DEFLATE resp=Content-Type $image/svg+xml
FilterProvider COMPRESS DEFLATE resp=Content-Type $image/x-icon
FilterProvider COMPRESS DEFLATE resp=Content-Type $application/x-font-ttf
FilterProvider COMPRESS DEFLATE resp=Content-Type $font/opentype
FilterChain COMPRESS
FilterProtocol COMPRESS DEFLATE change=yes;byteranges=no
</IfModule>
<IfModule !mod_filter.c>
# Legacy versions of Apache
AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
</IfModule>
</IfModule>
# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------
# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
# www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week" or so.
# <IfModule mod_expires.c>
# ExpiresActive on
# Perhaps better to whitelist expires rules? Perhaps.
# ExpiresDefault "access plus 1 month"
# cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5)
# ExpiresByType text/cache-manifest "access plus 0 seconds"
# Your document html
# ExpiresByType text/html "access plus 0 seconds"
# Data
# ExpiresByType text/xml "access plus 0 seconds"
# ExpiresByType application/xml "access plus 0 seconds"
# ExpiresByType application/json "access plus 0 seconds"
# Feed
# ExpiresByType application/rss+xml "access plus 1 hour"
# ExpiresByType application/atom+xml "access plus 1 hour"
# Favicon (cannot be renamed)
# ExpiresByType image/x-icon "access plus 1 week"
# Media: images, video, audio
# ExpiresByType image/gif "access plus 1 month"
# ExpiresByType image/png "access plus 1 month"
# ExpiresByType image/jpg "access plus 1 month"
# ExpiresByType image/jpeg "access plus 1 month"
# ExpiresByType video/ogg "access plus 1 month"
# ExpiresByType audio/ogg "access plus 1 month"
# ExpiresByType video/mp4 "access plus 1 month"
# ExpiresByType video/webm "access plus 1 month"
# HTC files (css3pie)
# ExpiresByType text/x-component "access plus 1 month"
# Webfonts
# ExpiresByType application/x-font-ttf "access plus 1 month"
# ExpiresByType font/opentype "access plus 1 month"
# ExpiresByType application/x-font-woff "access plus 1 month"
# ExpiresByType image/svg+xml "access plus 1 month"
# ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
# CSS and JavaScript
# ExpiresByType text/css "access plus 1 year"
# ExpiresByType application/javascript "access plus 1 year"
# </IfModule>
# ----------------------------------------------------------------------
# Prevent mobile network providers from modifying your site
# ----------------------------------------------------------------------
# The following header prevents modification of your code over 3G on some European providers
# This is the official 'bypass' suggested by O2 in the UK
# <IfModule mod_headers.c>
# Header set Cache-Control "no-transform"
# </IfModule>
# ----------------------------------------------------------------------
# ETag removal
# ----------------------------------------------------------------------
# FileETag None is not enough for every server.
# <IfModule mod_headers.c>
# Header unset ETag
# </IfModule>
# Since we're sending far-future expires, we don't need ETags for
# static content.
# developer.yahoo.com/performance/rules.html#etags
# FileETag None
# ----------------------------------------------------------------------
# Stop screen flicker in IE on CSS rollovers
# ----------------------------------------------------------------------
# The following directives stop screen flicker in IE on CSS rollovers - in
# combination with the "ExpiresByType" rules for images (see above). If
# needed, un-comment the following rules.
# BrowserMatch "MSIE" brokenvary=1
# BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1
# BrowserMatch "Opera" !brokenvary
# SetEnvIf brokenvary 1 force-no-vary
# ----------------------------------------------------------------------
# Set Keep-Alive Header
# ----------------------------------------------------------------------
# Keep-Alive allows the server to send multiple requests through one TCP-connection.
# Be aware of possible disadvantages of this setting. Turn on if you serve a lot of
# static content.
# <IfModule mod_headers.c>
# Header set Connection Keep-Alive
# </IfModule>
# ----------------------------------------------------------------------
# Cookie setting from iframes
# ----------------------------------------------------------------------
# Allow cookies to be set from iframes (for IE only)
# If needed, uncomment and specify a path or regex in the Location directive
# <IfModule mod_headers.c>
# Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""
# </IfModule>
# ----------------------------------------------------------------------
# Start rewrite engine
# ----------------------------------------------------------------------
# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
#
# Some cloud hosting services require RewriteBase to be set: goo.gl/HOcPN
# If using the h5bp in a subdirectory, use `RewriteBase /foo` instead where 'foo' is your directory.
# <IfModule mod_rewrite.c>
# Options +FollowSymlinks
# RewriteEngine On
# # RewriteBase /
# </IfModule>
# ----------------------------------------------------------------------
# Suppress or force the "www." at the beginning of URLs
# ----------------------------------------------------------------------
# The same content should never be available under two different URLs - especially not with and
# without "www." at the beginning, since this can cause SEO problems (duplicate content).
# That's why you should choose one of the alternatives and redirect the other one.
# By default option 1 (no "www.") is activated. Remember: Shorter URLs are sexier.
# no-www.org/faq.php?q=class_b
# If you rather want to use option 2, just comment out all option 1 lines
# and uncomment option 2.
# IMPORTANT: NEVER USE BOTH RULES AT THE SAME TIME!
# ----------------------------------------------------------------------
# Option 1:
# Rewrite "www.example.com -> example.com"
# <IfModule mod_rewrite.c>
# RewriteCond %{HTTPS} !=on
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
# </IfModule>
# ----------------------------------------------------------------------
# Option 2:
# To rewrite "example.com -> www.example.com" uncomment the following lines.
# Be aware that the following rule might not be a good idea if you
# use "real" subdomains for certain parts of your website.
# <IfModule mod_rewrite.c>
# RewriteCond %{HTTPS} !=on
# RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# </IfModule>
# ----------------------------------------------------------------------
# Built-in filename-based cache busting
# ----------------------------------------------------------------------
# If you're not using the build script to manage your filename version revving,
# you might want to consider enabling this, which will route requests for
# /css/style.20110203.css to /css/style.css
# To understand why this is important and a better idea than all.css?v1231,
# read: github.com/h5bp/html5-boilerplate/wiki/cachebusting
# Uncomment to enable.
# <IfModule mod_rewrite.c>
# RewriteCond %{REQUEST_FILENAME} !-f
# RewriteCond %{REQUEST_FILENAME} !-d
# RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]
# </IfModule>
# ----------------------------------------------------------------------
# Prevent SSL cert warnings
# ----------------------------------------------------------------------
# Rewrite secure requests properly to prevent SSL cert warnings, e.g. prevent
# https://www.example.com when your cert only allows https://secure.example.com
# Uncomment the following lines to use this feature.
# <IfModule mod_rewrite.c>
# RewriteCond %{SERVER_PORT} !^443
# RewriteRule ^ https://example-domain-please-change-me.com%{REQUEST_URI} [R=301,L]
# </IfModule>
# ----------------------------------------------------------------------
# Prevent 404 errors for non-existing redirected folders
# ----------------------------------------------------------------------
# without -MultiViews, Apache will give a 404 for a rewrite if a folder of the same name does not exist
# e.g. /blog/hello : webmasterworld.com/apache/3808792.htm
# Options -MultiViews
# ----------------------------------------------------------------------
# Custom 404 page
# ----------------------------------------------------------------------
# You can add custom pages to handle 500 or 403 pretty easily, if you like.
# If you are hosting your site in subdirectory, adjust this accordingly
# e.g. ErrorDocument 404 /subdir/404.html
# ErrorDocument 404 /404.html
# ----------------------------------------------------------------------
# UTF-8 encoding
# ----------------------------------------------------------------------
# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8
# Force UTF-8 for a number of file formats
AddCharset utf-8 .css .js .xml .json .rss .atom
# ----------------------------------------------------------------------
# A little more security
# ----------------------------------------------------------------------
# Do we want to advertise the exact version number of Apache we're running?
# Probably not.
## This can only be enabled if used in httpd.conf - It will not work in .htaccess
# ServerTokens Prod
# "-Indexes" will have Apache block users from browsing folders without a default document
# Usually you should leave this activated, because you shouldn't allow everybody to surf through
# every folder on your server (which includes rather private places like CMS system folders).
<IfModule mod_autoindex.c>
Options -Indexes
</IfModule>
# Block access to "hidden" directories or files whose names begin with a period. This
# includes directories used by version control systems such as Subversion or Git.
<IfModule mod_rewrite.c>
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]
</IfModule>
# Block access to backup and source files
# This files may be left by some text/html editors and
# pose a great security danger, when someone can access them
<FilesMatch "(\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$">
Order allow,deny
Deny from all
Satisfy All
</FilesMatch>
# Block access to WordPress files that reveal version information.
<FilesMatch "^(wp-config\.php|readme\.html|license\.txt)">
Order allow,deny
Deny from all
Satisfy All
</FilesMatch>
# If your server is not already configured as such, the following directive
# should be uncommented in order to set PHP's register_globals option to OFF.
# This closes a major security hole that is abused by most XSS (cross-site
# scripting) attacks. For more information: http://php.net/register_globals
#
# IF REGISTER_GLOBALS DIRECTIVE CAUSES 500 INTERNAL SERVER ERRORS :
#
# Your server does not allow PHP directives to be set via .htaccess. In that
# case you must make this change in your php.ini file instead. If you are
# using a commercial web host, contact the administrators for assistance in
# doing this. Not all servers allow local php.ini files, and they should
# include all PHP configurations (not just this one), or you will effectively
# reset everything to PHP defaults. Consult www.php.net for more detailed
# information about setting PHP directives.
# php_flag register_globals Off
# Rename session cookie to something else, than PHPSESSID
# php_value session.name sid
# Disable magic quotes (This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.)
# php_flag magic_quotes_gpc Off
# Do not show you are using PHP
# Note: Move this line to php.ini since it won't work in .htaccess
# php_flag expose_php Off
# Level of log detail - log all errors
# php_value error_reporting -1
# Write errors to log file
# php_flag log_errors On
# Do not display errors in browser (production - Off, development - On)
# php_flag display_errors Off
# Do not display startup errors (production - Off, development - On)
# php_flag display_startup_errors Off
# Format errors in plain text
# Note: Leave this setting 'On' for xdebug's var_dump() output
# php_flag html_errors Off
# Show multiple occurrence of error
# php_flag ignore_repeated_errors Off
# Show same errors from different sources
# php_flag ignore_repeated_source Off
# Size limit for error messages
# php_value log_errors_max_len 1024
# Don't precede error with string (doesn't accept empty string, use whitespace if you need)
# php_value error_prepend_string " "
# Don't prepend to error (doesn't accept empty string, use whitespace if you need)
# php_value error_append_string " "
# Increase cookie security
<IfModule php5_module>
php_value session.cookie_httponly true
</IfModule>
# END HTML5 Boilerplate

96
lib/htaccess.php Normal file
View File

@@ -0,0 +1,96 @@
<?php
/**
* URL rewriting and addition of HTML5 Boilerplate's .htaccess
*
* Rewrites currently do not happen for child themes (or network installs)
* @todo https://github.com/retlehs/roots/issues/461
*
* Rewrite:
* /wp-content/themes/themename/css/ to /css/
* /wp-content/themes/themename/js/ to /js/
* /wp-content/themes/themename/img/ to /img/
* /wp-content/plugins/ to /plugins/
*
* If you aren't using Apache, alternate configuration settings can be found in the wiki.
*
* @link https://github.com/retlehs/roots/wiki/Nginx
* @link https://github.com/retlehs/roots/wiki/Lighttpd
*/
if (stristr($_SERVER['SERVER_SOFTWARE'], 'apache') || stristr($_SERVER['SERVER_SOFTWARE'], 'litespeed') !== false) {
// Show an admin notice if .htaccess isn't writable
function roots_htaccess_writable() {
if (!is_writable(get_home_path() . '.htaccess')) {
if (current_user_can('administrator')) {
add_action('admin_notices', create_function('', "echo '<div class=\"error\"><p>" . sprintf(__('Please make sure your <a href="%s">.htaccess</a> file is writable ', 'roots'), admin_url('options-permalink.php')) . "</p></div>';"));
}
}
}
add_action('admin_init', 'roots_htaccess_writable');
function roots_add_rewrites($content) {
global $wp_rewrite;
$roots_new_non_wp_rules = array(
'css/(.*)' => THEME_PATH . '/css/$1',
'js/(.*)' => THEME_PATH . '/js/$1',
'img/(.*)' => THEME_PATH . '/img/$1',
'plugins/(.*)' => RELATIVE_PLUGIN_PATH . '/$1'
);
$wp_rewrite->non_wp_rules = array_merge($wp_rewrite->non_wp_rules, $roots_new_non_wp_rules);
return $content;
}
function roots_clean_urls($content) {
if (strpos($content, FULL_RELATIVE_PLUGIN_PATH) === 0) {
return str_replace(FULL_RELATIVE_PLUGIN_PATH, WP_BASE . '/plugins', $content);
} else {
return str_replace('/' . THEME_PATH, '', $content);
}
}
if (!is_multisite() && !is_child_theme() && get_option('permalink_structure')) {
if (current_theme_supports('rewrite-urls')) {
add_action('generate_rewrite_rules', 'roots_add_rewrites');
}
if (current_theme_supports('h5bp-htaccess')) {
add_action('generate_rewrite_rules', 'roots_add_h5bp_htaccess');
}
if (!is_admin() && current_theme_supports('rewrite-urls')) {
$tags = array(
'plugins_url',
'bloginfo',
'stylesheet_directory_uri',
'template_directory_uri',
'script_loader_src',
'style_loader_src'
);
add_filters($tags, 'roots_clean_urls');
}
}
// Add the contents of h5bp-htaccess into the .htaccess file
function roots_add_h5bp_htaccess($content) {
global $wp_rewrite;
$home_path = function_exists('get_home_path') ? get_home_path() : ABSPATH;
$htaccess_file = $home_path . '.htaccess';
$mod_rewrite_enabled = function_exists('got_mod_rewrite') ? got_mod_rewrite() : false;
if ((!file_exists($htaccess_file) && is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks()) || is_writable($htaccess_file)) {
if ($mod_rewrite_enabled) {
$h5bp_rules = extract_from_markers($htaccess_file, 'HTML5 Boilerplate');
if ($h5bp_rules === array()) {
$filename = dirname(__FILE__) . '/h5bp-htaccess';
return insert_with_markers($htaccess_file, 'HTML5 Boilerplate', extract_from_markers($filename, 'HTML5 Boilerplate'));
}
}
}
return $content;
}
}

46
lib/scripts.php Normal file
View File

@@ -0,0 +1,46 @@
<?php
/**
* Scripts and stylesheets
*
* Enqueue stylesheets in the following order:
* 1. /theme/css/bootstrap.css
* 2. /theme/css/bootstrap-responsive.css
* 3. /theme/css/app.css
* 4. /child-theme/style.css (if a child theme is activated)
*
* Enqueue scripts in the following order:
* 1. /theme/js/vendor/modernizr-2.6.1.min.js (in head.php)
* 2. jquery-1.8.0.min.js via Google CDN (in head.php)
* 3. /theme/js/plugins.js
* 4. /theme/js/main.js
*/
function roots_scripts() {
wp_enqueue_style('roots_bootstrap', get_template_directory_uri() . '/css/bootstrap.css', false, null);
wp_enqueue_style('roots_bootstrap_responsive', get_template_directory_uri() . '/css/bootstrap-responsive.css', array('roots_bootstrap'), null);
wp_enqueue_style('roots_app', get_template_directory_uri() . '/css/app.css', false, null);
// Load style.css from child theme
if (is_child_theme()) {
wp_enqueue_style('roots_child', get_stylesheet_uri(), false, null);
}
// jQuery is loaded in header.php using the same method from HTML5 Boilerplate:
// Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline
// It's kept in the header instead of footer to avoid conflicts with plugins.
if (!is_admin()) {
wp_deregister_script('jquery');
wp_register_script('jquery', '', '', '', false);
}
if (is_single() && comments_open() && get_option('thread_comments')) {
wp_enqueue_script('comment-reply');
}
wp_register_script('roots_plugins', get_template_directory_uri() . '/js/plugins.js', false, null, false);
wp_register_script('roots_main', get_template_directory_uri() . '/js/main.js', false, null, false);
wp_enqueue_script('roots_plugins');
wp_enqueue_script('roots_main');
}
add_action('wp_enqueue_scripts', 'roots_scripts', 100);

7
lib/template-tags.php Normal file
View File

@@ -0,0 +1,7 @@
<?php
// Return post entry meta information
function roots_entry_meta() {
echo '<time class="updated" datetime="'. get_the_time('c') .'" pubdate>'. sprintf(__('Posted on %s at %s.', 'roots'), get_the_date(), get_the_time()) .'</time>';
echo '<p class="byline author vcard">'. __('Written by', 'roots') .' <a href="'. get_author_posts_url(get_the_author_meta('ID')) .'" rel="author" class="fn">'. get_the_author() .'</a></p>';
}

65
lib/utils.php Normal file
View File

@@ -0,0 +1,65 @@
<?php
/**
* Theme Wrapper
*
* @link http://scribu.net/wordpress/theme-wrappers.html
*/
function roots_template_path() {
return Roots_Wrapping::$main_template;
}
class Roots_Wrapping {
// Stores the full path to the main template file
static $main_template;
// Stores the base name of the template file; e.g. 'page' for 'page.php' etc.
static $base;
static function wrap($template) {
self::$main_template = $template;
self::$base = substr(basename(self::$main_template), 0, -4);
if ('index' == self::$base) {
self::$base = false;
}
$templates = array('base.php');
if (self::$base) {
array_unshift($templates, sprintf('base-%s.php', self::$base ));
}
return locate_template($templates);
}
}
add_filter('template_include', array('Roots_Wrapping', 'wrap'), 99);
// returns WordPress subdirectory if applicable
function wp_base_dir() {
preg_match('!(https?://[^/|"]+)([^"]+)?!', site_url(), $matches);
if (count($matches) === 3) {
return end($matches);
} else {
return '';
}
}
// opposite of built in WP functions for trailing slashes
function leadingslashit($string) {
return '/' . unleadingslashit($string);
}
function unleadingslashit($string) {
return ltrim($string, '/');
}
function add_filters($tags, $function) {
foreach($tags as $tag) {
add_filter($tag, $function);
}
}

153
lib/widgets.php Normal file
View File

@@ -0,0 +1,153 @@
<?php
function roots_widgets_init() {
// Register widgetized areas
register_sidebar(array(
'name' => __('Primary Sidebar', 'roots'),
'id' => 'sidebar-primary',
'before_widget' => '<section id="%1$s" class="widget %2$s"><div class="widget-inner">',
'after_widget' => '</div></section>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
register_sidebar(array(
'name' => __('Footer', 'roots'),
'id' => 'sidebar-footer',
'before_widget' => '<section id="%1$s" class="widget %2$s"><div class="widget-inner">',
'after_widget' => '</div></section>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
// Register widgets
register_widget('Roots_Vcard_Widget');
}
add_action('widgets_init', 'roots_widgets_init');
// Example vCard widget
class Roots_Vcard_Widget extends WP_Widget {
function Roots_Vcard_Widget() {
$widget_ops = array('classname' => 'widget_roots_vcard', 'description' => __('Use this widget to add a vCard', 'roots'));
$this->WP_Widget('widget_roots_vcard', __('Roots: vCard', 'roots'), $widget_ops);
$this->alt_option_name = 'widget_roots_vcard';
add_action('save_post', array(&$this, 'flush_widget_cache'));
add_action('deleted_post', array(&$this, 'flush_widget_cache'));
add_action('switch_theme', array(&$this, 'flush_widget_cache'));
}
function widget($args, $instance) {
$cache = wp_cache_get('widget_roots_vcard', 'widget');
if (!is_array($cache)) {
$cache = array();
}
if (!isset($args['widget_id'])) {
$args['widget_id'] = null;
}
if (isset($cache[$args['widget_id']])) {
echo $cache[$args['widget_id']];
return;
}
ob_start();
extract($args, EXTR_SKIP);
$title = apply_filters('widget_title', empty($instance['title']) ? __('vCard', 'roots') : $instance['title'], $instance, $this->id_base);
if (!isset($instance['street_address'])) { $instance['street_address'] = ''; }
if (!isset($instance['locality'])) { $instance['locality'] = ''; }
if (!isset($instance['region'])) { $instance['region'] = ''; }
if (!isset($instance['postal_code'])) { $instance['postal_code'] = ''; }
if (!isset($instance['tel'])) { $instance['tel'] = ''; }
if (!isset($instance['email'])) { $instance['email'] = ''; }
echo $before_widget;
if ($title) {
echo $before_title;
echo $title;
echo $after_title;
}
?>
<p class="vcard">
<a class="fn org url" href="<?php echo home_url('/'); ?>"><?php bloginfo('name'); ?></a><br>
<span class="adr">
<span class="street-address"><?php echo $instance['street_address']; ?></span><br>
<span class="locality"><?php echo $instance['locality']; ?></span>,
<span class="region"><?php echo $instance['region']; ?></span>
<span class="postal-code"><?php echo $instance['postal_code']; ?></span><br>
</span>
<span class="tel"><span class="value"><?php echo $instance['tel']; ?></span></span><br>
<a class="email" href="mailto:<?php echo $instance['email']; ?>"><?php echo $instance['email']; ?></a>
</p>
<?php
echo $after_widget;
$cache[$args['widget_id']] = ob_get_flush();
wp_cache_set('widget_roots_vcard', $cache, 'widget');
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['street_address'] = strip_tags($new_instance['street_address']);
$instance['locality'] = strip_tags($new_instance['locality']);
$instance['region'] = strip_tags($new_instance['region']);
$instance['postal_code'] = strip_tags($new_instance['postal_code']);
$instance['tel'] = strip_tags($new_instance['tel']);
$instance['email'] = strip_tags($new_instance['email']);
$this->flush_widget_cache();
$alloptions = wp_cache_get('alloptions', 'options');
if (isset($alloptions['widget_roots_vcard'])) {
delete_option('widget_roots_vcard');
}
return $instance;
}
function flush_widget_cache() {
wp_cache_delete('widget_roots_vcard', 'widget');
}
function form($instance) {
$title = isset($instance['title']) ? esc_attr($instance['title']) : '';
$street_address = isset($instance['street_address']) ? esc_attr($instance['street_address']) : '';
$locality = isset($instance['locality']) ? esc_attr($instance['locality']) : '';
$region = isset($instance['region']) ? esc_attr($instance['region']) : '';
$postal_code = isset($instance['postal_code']) ? esc_attr($instance['postal_code']) : '';
$tel = isset($instance['tel']) ? esc_attr($instance['tel']) : '';
$email = isset($instance['email']) ? esc_attr($instance['email']) : '';
?>
<p>
<label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php _e('Title (optional):', 'roots'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>" />
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('street_address')); ?>"><?php _e('Street Address:', 'roots'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('street_address')); ?>" name="<?php echo esc_attr($this->get_field_name('street_address')); ?>" type="text" value="<?php echo esc_attr($street_address); ?>" />
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('locality')); ?>"><?php _e('City/Locality:', 'roots'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('locality')); ?>" name="<?php echo esc_attr($this->get_field_name('locality')); ?>" type="text" value="<?php echo esc_attr($locality); ?>" />
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('region')); ?>"><?php _e('State/Region:', 'roots'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('region')); ?>" name="<?php echo esc_attr($this->get_field_name('region')); ?>" type="text" value="<?php echo esc_attr($region); ?>" />
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('postal_code')); ?>"><?php _e('Zipcode/Postal Code:', 'roots'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('postal_code')); ?>" name="<?php echo esc_attr($this->get_field_name('postal_code')); ?>" type="text" value="<?php echo esc_attr($postal_code); ?>" />
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('tel')); ?>"><?php _e('Telephone:', 'roots'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('tel')); ?>" name="<?php echo esc_attr($this->get_field_name('tel')); ?>" type="text" value="<?php echo esc_attr($tel); ?>" />
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('email')); ?>"><?php _e('Email:', 'roots'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('email')); ?>" name="<?php echo esc_attr($this->get_field_name('email')); ?>" type="text" value="<?php echo esc_attr($email); ?>" />
</p>
<?php
}
}