Шорткоды (англ.shortcodes) это короткие коды для вызова функций. Функции могут быть в теме, можно написать самому. Удобство заключается в том, что не надо писать в шаблон кучу строк кода, достаточно кинуть файл functions.php и подключать нужные функции простым вызовом макроса [function].
1. Related Posts
function related_posts_shortcode( $atts ) {
extract(shortcode_atts(array(
'limit' => '5',
), $atts));
global $wpdb, $post, $table_prefix;
if ($post->ID) {
$retval = '<ul>';
// Get tags
$tags = wp_get_post_tags($post->ID);
$tagsarray = array();
foreach ($tags as $tag) {
$tagsarray[] = $tag->term_id;
}
$tagslist = implode(',', $tagsarray);
// Do the query
$q = "SELECT p.*, count(tr.object_id) as count
FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID
AND p.post_status = 'publish'
AND p.post_date_gmt < NOW()
GROUP BY tr.object_id
ORDER BY count DESC, p.post_date_gmt DESC
LIMIT $limit;";
$related = $wpdb->get_results($q);
if ( $related ) {
foreach($related as $r) {
$retval .= '<li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>';
}
} else {
$retval .= '
<li>No related posts found</li>';
}
$retval .= '</ul>';
return $retval;
}
return;
}
add_shortcode('related_posts', 'related_posts_shortcode');
Использование:
в нужном месте поста просто добавляем
[related_posts]
Добавляем контекстную рекламу
на примере адсенса
function showads() {
return '<script type="text/javascript"><!--
google_ad_client = "pub-3637220125174754";
google_ad_slot = "4668915978";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
';
}
add_shortcode('adsense', 'showads');
Вызов:
[adsense]
Добавляем RSS
Например, можно добавить в пост свою или чью либо рсс-ленту
//This file is needed to be able to use the wp_rss() function.
include_once(ABSPATH.WPINC.'/rss.php');
function readRss($atts) {
extract(shortcode_atts(array(
"feed" => 'http://',
"num" => '1',
), $atts));
return wp_rss($feed, $num);
}
add_shortcode('rss', 'readRss');
Вызов:
[rss feed="http://feeds2.feedburner.com/Catswhocode" num="5"]
Показываем последнее изображение поста
Можно выводить превьюшки на главной.
function sc_postimage($atts, $content = null) {
extract(shortcode_atts(array(
"size" => 'thumbnail',
"float" => 'none'
), $atts));
$images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );
foreach( $images as $imageID => $imagePost )
$fullimage = wp_get_attachment_image($imageID, $size, false);
$imagedata = wp_get_attachment_image_src($imageID, $size, false);
$width = ($imagedata[1]+2);
$height = ($imagedata[2]+2);
return '<div style="width: '.$width.'px; height: '.$height.'px; float: '.$float.';">'.$fullimage.'</div>';
}
add_shortcode("postimage", "sc_postimage");
Вызов:
[postimage]
Отключение встроенного форматирования вордпрессом текста
function my_formatter($content) {
$new_content = '';
$pattern_full = '{(\[raw\].*?\[/raw\])}is';
$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($pieces as $piece) {
if (preg_match($pattern_contents, $piece, $matches)) {
$new_content .= $matches[1];
} else {
$new_content .= wptexturize(wpautop($piece));
}
}
return $new_content;
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');
add_filter('the_content', 'my_formatter', 99);
Использование:
[raw]This portion of text will not be automatically formatted by WP.[/raw]
Отображение статистики блога
Для фанатов мерятся показателями. Устанавливаем вот этот плагин и кучу шорткодов:
[pagerank] [feedburner_subscribers] [alexa_rank] [technorati_authority] [technorati_rank] [user_count] [post_count] [page_count] [comment_count] [trackback_count] [avg_comments_per_post] [category_count] [tag_count] [link_count] [google_backlinks] [yahoo_backlinks] [delicious_bookmarks]
Оригинал статьи + еще некоторые шорткоды здесь
7 responses
Do you want to comment?
Comments RSS and TrackBack Identifier URI ?
Trackbacks