Upload
graham-armfield
View
459
Download
0
Embed Size (px)
Citation preview
Coolfields Consulting www.coolfields.co.uk@coolfields
Obscure WordPress Functions that are actually quite useful…Graham ArmfieldWeb Accessibility ConsultantWordPress Developer
[email protected]@coolfields
2
Obscure? Really?
Well, maybe not known to everyone…
3
Formatting textwpautop($str);
• Adds in line breaks and paragraphs
• Useful for printing textarea custom fields
4
Formatting textBut… sometimes wpautop() goes too far
• Adds in empty paragraphs• <div> elements in paragraphs• Often happens when using shortcodes• Can be down to the order that things get
done
5
Removing empty paragraphsremove_filter( 'the_content', 'wpautop' );add_filter( 'the_content', 'wpautop' , 99);
function remove_empty_p($content){ $content = force_balance_tags($content); return preg_replace('#<p>\s*+(<br\s*/*>)?\s*</p>#i', '', $content);}add_filter('the_content', 'remove_empty_p', 20, 1);
6
More on shortcodesAllow shortcodes to be interpreted in widgets:
add_filter('widget_text', 'do_shortcode');
Remove all shortcodes from a string:
strip_shortcodes( $content );
7
ExcerptsThe default length is 55 words.
You can change this…
function custom_excerpt_length( $length ) {return 30;
}add_filter( 'excerpt_length', custom_excerpt_length', 999 );
8
Localizing datesPost/page published dates get localized automatically by WP when site's language changes.
But, what if you have to set date formats in PHP?
9
Localizing datesEg: Custom fields may have date in database format: 2016-02-25
This is useful for sorting, and selecting using wp_query();
You may need to output: 25 Chwefror 2016
10
Localizing datesSetting the locale in PHP can be a pain.
So use the WordPress capability instead –
date_i18n($pattern, $timestamp);
11
Localizing datesfunction db_date_format($str_date, $pattern = ''){ // incoming format = yyyy-mm-dd if (empty($pattern)) { $pattern = get_option( 'date_format' ); }
$time_stamp = mktime(0,0,0,substr($str_date,5,2), substr ($str_date,8,2),substr($str_date,0,4));
return date_i18n( $pattern, $time_stamp );}
12
PaginationOn blog index pages, using previous_posts_link() and next_posts_link() is OK…
But it doesn't give site visitors an indication of how many blog posts there are altogether.
Pagination may give better usability…
13
Paginationglobal $wp_query;
if ($wp_query->max_num_pages > 1) { $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link($big) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'end_size' => 3, 'type' => 'list', 'prev_text' => '« Newer<span class="srdr"> posts</span>', 'next_text' => 'Older<span class="srdr"> posts</span> »', 'before_page_number' => '<span class="srdr">Page </span>', 'after_page_number' => '' ) );}
Can use this with custom queries too.