20个有用的WordPress函数代码

发布时间:2020-05-05
  • Facebook Share Button
  • Digg it
  • Stumble upon it
  • Add to delicious
  • Share on technorati
  • Tweet this

目录

More and more clients are using wordpress as their CMS. As a designer or developer, you should really get into wordpress coding. To get started, you can read my wordpress theme guide and hacks. Now, I would like to recommend a resourceful wordpress site to you called WpRecipes. This post contains over 20 recipes that I hand picked from WpRecipes. If you have any good wordpress code or hacks that you want to share, feel free to send them over and I will post it.

先粘过来,研究明白再翻译一下,哈!

Display Tags In A Dropdown Menu

In your theme folder, paste the following code to the functions.php file. If you don’t have a functions.php file, create one.

<?php function dropdown_tag_cloud( $args = '' ) { 	$defaults = array( 		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45, 		'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC', 		'exclude' => '', 'include' => '' 	); 	$args = wp_parse_args( $args, $defaults );  	$tags = get_tags( array_merge($args, array('orderby' => 'count', 'order' => 'DESC')) ); // Always query top tags  	if ( empty($tags) ) 		return;  	$return = dropdown_generate_tag_cloud( $tags, $args ); // Here's where those top tags get sorted according to $args 	if ( is_wp_error( $return ) ) 		return false; 	else 		echo apply_filters( 'dropdown_tag_cloud', $return, $args ); }  function dropdown_generate_tag_cloud( $tags, $args = '' ) { 	global $wp_rewrite; 	$defaults = array( 		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45, 		'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC' 	); 	$args = wp_parse_args( $args, $defaults ); 	extract($args);  	if ( !$tags ) 		return; 	$counts = $tag_links = array(); 	foreach ( (array) $tags as $tag ) { 		$counts[$tag->name] = $tag->count; 		$tag_links[$tag->name] = get_tag_link( $tag->term_id ); 		if ( is_wp_error( $tag_links[$tag->name] ) ) 			return $tag_links[$tag->name]; 		$tag_ids[$tag->name] = $tag->term_id; 	}  	$min_count = min($counts); 	$spread = max($counts) - $min_count; 	if ( $spread <= 0 ) 		$spread = 1; 	$font_spread = $largest - $smallest; 	if ( $font_spread <= 0 ) 		$font_spread = 1; 	$font_step = $font_spread / $spread;  	// SQL cannot save you; this is a second (potentially different) sort on a subset of data. 	if ( 'name' == $orderby ) 		uksort($counts, 'strnatcasecmp'); 	else 		asort($counts);  	if ( 'DESC' == $order ) 		$counts = array_reverse( $counts, true );  	$a = array();  	$rel = ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) ? ' rel="tag"' : '';  	foreach ( $counts as $tag => $count ) { 		$tag_id = $tag_ids[$tag]; 		$tag_link = clean_url($tag_links[$tag]); 		$tag = str_replace(' ', '&nbsp;', wp_specialchars( $tag )); 		$a[] = "t<option value='$tag_link'>$tag ($count)</option>"; 	}  	switch ( $format ) : 	case 'array' : 		$return =& $a; 		break; 	case 'list' : 		$return = "<ul class='wp-tag-cloud'>nt<li>"; 		$return .= join("</li>nt<li>", $a); 		$return .= "</li>n</ul>n"; 		break; 	default : 		$return = join("n", $a); 		break; 	endswitch;  	return apply_filters( 'dropdown_generate_tag_cloud', $return, $tags, $args ); } ?>

Now open the file where you want the list to be displayed and paste the following code:

<select name="tag-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;"> 	<option value="#">Tags</option> 	<?php dropdown_tag_cloud('number=0&order=asc'); ?> </select>

Via: WpRecipes Credits: WpHacks

Get Posts Published Between Two Particular Dates

Just before the loop starts, paste the following code. Change the dates on line 3 according to your needs.

<?php   function filter_where($where = '') {         $where .= " AND post_date >= '2009-05-01' AND post_date <= '2009-05-15'";     return $where;   } add_filter('posts_where', 'filter_where'); query_posts($query_string); ?>

Via: WpRecipes Credits: Codex

Get Posts With A Specific Custom Field & Value

Add the query_posts() function just before the Loop. Change the meta_key and meta_value accordingly. The example shown below will get posts with custom field “review_type” with value “movie”.

<?php query_posts('meta_key=review_type&meta_value=movie');  ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> ... ...

Via: WpRecipes Credits: John Kolbert

Get Latest Sticky Posts

Paste the following code before the loop. This code will retrieve the 5 most recent sticky posts. To change the number of retrieved posts, just change the 5 by the desired value on line 4.

<?php 	$sticky = get_option('sticky_posts'); 	rsort( $sticky ); 	$sticky = array_slice( $sticky, 0, 5);         query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) ); ?> 

Via: WpRecipes Credits: Justin Tadlock

Automatically Insert Content In Your Feeds

In your theme folder, functions.php file, paste the following code. This code will automatically insert the content after each post in your RSS feeds. Hence you can use this code to insert ads or promotional text.

function insertFootNote($content) {         if(!is_feed() && !is_home()) {                 $content.= "<h4>Enjoyed this article?</h4>";                 $content.= "<p>Subscribe to our <a href='#'>RSS feed</a></p>";         }         return $content; } add_filter ('the_content', 'insertFootNote');  

Via: WpRecipes Credits: Cédric Bousmane

Display The Most Commented Posts

Just paste the following code in your template file where you want to display the most commented posts (eg. sidebar.php). To change the number of displayed posts, simply change the 5 on line 3.

<h2>Popular Posts</h2> <ul> <?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5"); foreach ($result as $post) { setup_postdata($post); $postid = $post->ID; $title = $post->post_title; $commentcount = $post->comment_count; if ($commentcount != 0) { ?>  <li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>"> <?php echo $title ?></a> {<?php echo $commentcount ?>}</li> <?php } } ?>  </ul> 

Via: WpRecipes Credits: ProBlogDesign

Display Most Commented Posts In 2008

<h2>Most commented posts from 2008</h2> <ul> <?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN '2008-01-01' AND '2008-12-31' ORDER BY comment_count DESC LIMIT 0 , 10");  foreach ($result as $topten) {     $postid = $topten->ID;     $title = $topten->post_title;     $commentcount = $topten->comment_count;     if ($commentcount != 0) {     ?>          <li><a href="<?php echo get_permalink($postid); ?>"><?php echo $title ?></a></li>      <?php } } ?> </ul> 

Via: WpRecipes

Display Related Posts Based On Post Tags

This code will display related posts based on the current post tag(s). It must be pasted within the loop.

<?php //for use in the loop, list 5 post titles related to first tag on current post $tags = wp_get_post_tags($post->ID); if ($tags) {   echo 'Related Posts';   $first_tag = $tags[0]->term_id;   $args=array(     'tag__in' => array($first_tag),     'post__not_in' => array($post->ID),     'showposts'=>5,     'caller_get_posts'=>1    );   $my_query = new WP_Query($args);   if( $my_query->have_posts() ) {     while ($my_query->have_posts()) : $my_query->the_post(); ?>        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>       <?php     endwhile;   } } ?> 

Via: WpRecipes Credits: MichaelH

Display The Number Of Search Results

Open search.php, copy and paste the following code.

<h2 class="pagetitle">Search Results for <?php /* Search Count */ $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('<span class="search-terms">'); echo $key; _e('</span>'); _e(' — '); echo $count . ' '; _e('articles'); wp_reset_query(); ?></h2> 

Via: WpRecipes Credits: ProBlogDesign

Display The Comment Page Number In The <Title> Tag

Open the header.php file. Paste the following code in between the <title> tag.

<?php if ( $cpage < 2 ) {} else { echo (' - comment page '); echo ($cpage);} ?> 

Via: WpRecipes Credits: Malcolm Coles

Display The Future Posts

The following code will display 10 future posts.

 	<p>Future events</p> 	<?php query_posts('showposts=10&post_status=future'); ?> 	<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>  			<p><?php the_title(); ?> <?php the_time('j. F Y'); ?></p>  	<?php endwhile; else: ?><p>No future posts.</p><?php endif; ?> 

Via: WpRecipes

Randomize Posts Order

To randomize posts order, just add the following code before the Loop.

query_posts('orderby=rand'); //the Loop here... 

Via: WpRecipes

Display Word Count Of The Post

Open single.php and paste the following code where you want to display the word count.

<?php function count_words($str){      $words = 0;      $str = eregi_replace(" +", " ", $str);      $array = explode(" ", $str);      for($i=0;$i < count($array);$i++)  	 {          if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $array[$i]))              $words++;      }      return $words;  }?>   Word count: <?php echo count_words($post->post_content); ?> 

Via: WpRecipes

Fetch RSS Feeds

To display RSS feeds, you can use the wordpress built-in RSS parser. To do so, include the rss.php file, and then use its wp_rss() function.

<?php include_once(ABSPATH.WPINC.'/rss.php'); wp_rss('http://feeds2.feedburner.com/WebDesignerWall', 5); ?> 

Via: WpRecipes

Highlight Searched Text In Search Results

Open search.php file and find the the_title() function. Replace it with the following:

echo $title;

Now, just before the modified line, add this code:

<?php 	$title 	= get_the_title(); 	$keys= explode(" ",$s); 	$title 	= preg_replace('/('.implode('|', $keys) .')/iu', 		'<strong class="search-excerpt"></strong>', 		$title); ?>

Then open the style.css file. Add the following line to it:

strong.search-excerpt { background: yellow; } 

Via: WpRecipes Credits: Joost de Valk

Display A Greeting Message On A Specific Date (PHP)

The following code will dispaly a greeting message only on Christmas day.

<?php if ((date('m') == 12) && (date('d') == 25)) { ?>     <h2>Merry Christmas!</h2> <?php } ?> 

Via: WpRecipes

Automatically Create A TinyURL For Each Post

Open the functions.php file and paste the following code:

function getTinyUrl($url) {     $tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url);     return $tinyurl; } 

In the single.php file, paste the following within the loop where you want to display the TinyURL:

<?php $turl = getTinyUrl(get_permalink($post->ID)); echo 'Tiny Url for this post: <a href="'.$turl.'">'.$turl.'</a>' ?> 

Via: WpRecipes

Exclude Categories From Search

Open the search.php file in your theme folder, paste the following code before the Loop. The code will exclude categories with ID 1, 2, 3 in the search results.

<?php if( is_search() )  : $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("s=$s&paged=$paged&cat=-1,-2,-3"); endif; ?>  //the Loop here... 

Via: WpRecipes

Exclude Categories From RSS

Open the functions.php file from your theme. If your theme doesn’t have a functions.php file, create one. Paste the following code in it:

<?php function myFilter($query) {     if ($query->is_feed) {         $query->set('cat','-5'); //Don't forget to change the category ID =^o^=     } return $query; }  add_filter('pre_get_posts','myFilter'); ?> 

Via: WpRecipes Credits: Scott Jangro

Using Shortcodes

Open the functions.php file, paste the following code.

<?php function wprecipes() {     return 'Have you checked out WpRecipes today?'; }  add_shortcode('wpr', 'wprecipes'); ?> 

You’re now able to use the wpr shortcode. To do so, paste the following line of code on the editor (in HTML mode) while writing a post:

[wpr]

This short code will output the “Have you checked out WpRecipes today?” message.

Via: WpRecipes Source: Codex

Display The Number Of Your Twitter Followers

Paste the code anywhere you want to display the Twitter follower count. Replace “YourUserID” with your Twitter account in last line.

<?php function string_getInsertedString($long_string,$short_string,$is_html=false){   if($short_string>=strlen($long_string))return false;   $insertion_length=strlen($long_string)-strlen($short_string);   for($i=0;$i<strlen($short_string);++$i){     if($long_string[$i]!=$short_string[$i])break;   }   $inserted_string=substr($long_string,$i,$insertion_length);   if($is_html && $inserted_string[$insertion_length-1]=='<'){     $inserted_string='<'.substr($inserted_string,0,$insertion_length-1);   }   return $inserted_string; }  function DOMElement_getOuterHTML($document,$element){   $html=$document->saveHTML();   $element->parentNode->removeChild($element);   $html2=$document->saveHTML();   return string_getInsertedString($html,$html2,true); }  function getFollowers($username){   $x = file_get_contents("http://twitter.com/".$username);   $doc = new DomDocument;   @$doc->loadHTML($x);   $ele = $doc->getElementById('follower_count');   $innerHTML=preg_replace('/^<[^>]*>(.*)<[^>]*>$/',"\1",DOMElement_getOuterHTML($doc,$ele));   return $innerHTML; } ?>  <?php echo getFollowers("YourUserID")." followers"; ?> 

Via: WpRecipes

Display FeedBurner Subscriber Count In Text

<?php 	$fburl="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=feed-id"; 	$ch = curl_init(); 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 	curl_setopt($ch, CURLOPT_URL, $fburl); 	$stored = curl_exec($ch); 	curl_close($ch); 	$grid = new SimpleXMLElement($stored); 	$rsscount = $grid->feed->entry['circulation']; 	echo $rsscount; ?>

Via: WpRecipes

Display The Latest Twitter Entry

Just paste this code in the template file (eg. sidebar.php) where you want to display the latest tweet.

<?php  // Your twitter username. $username = "TwitterUsername";  $prefix = "<h2>My last Tweet</h2>";  $suffix = "";  $feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";  function parse_feed($feed) {     $stepOne = explode("<content type="html">", $feed);     $stepTwo = explode("</content>", $stepOne[1]);     $tweet = $stepTwo[0];     $tweet = str_replace("&lt;", "<", $tweet);     $tweet = str_replace("&gt;", ">", $tweet);     return $tweet; }  $twitterFeed = file_get_contents($feed); echo stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix); ?>

Via: WpRecipes Credits: Ryan Barr

Social Buttons

Facebook Share Button

<a rel="external nofollow" target="_blank" href="https://zmingcx.com/wp-content/themes/begin/go.php?url=aHR0cDovL3d3dy5mYWNlYm9vay5jb20vc2hhcmVyLnBocD91PSZsdDs/cGhwIHRoZV9wZXJtYWxpbmsoKTs/Jmd0OyZhbXA7dD0mbHQ7P3BocCB0aGVfdGl0bGUoKTsgPyZndDs=">Share on Facebook</a>

Digg it

<a rel="external nofollow" target="_blank" href="https://zmingcx.com/wp-content/themes/begin/go.php?url=aHR0cDovL3d3dy5kaWdnLmNvbS9zdWJtaXQ/cGhhc2U9MiZhbXA7dXJsPSZsdDs/cGhwIHRoZV9wZXJtYWxpbmsoKTs/Jmd0Ow==">Digg It</a>

Stumble upon it

<a rel="external nofollow" target="_blank" href="https://zmingcx.com/wp-content/themes/begin/go.php?url=aHR0cDovL3d3dy5zdHVtYmxldXBvbi5jb20vc3VibWl0P3VybD0mbHQ7P3BocCB0aGVfcGVybWFsaW5rKCk7ID8mZ3Q7JmFtcDt0aXRsZT0mbHQ7P3BocCB0aGVfdGl0bGUoKTsgPyZndDs=">Stumble upon it</a>

Add to delicious

<a rel="external nofollow" target="_blank" href="https://zmingcx.com/wp-content/themes/begin/go.php?url=aHR0cDovL2RlbGljaW91cy5jb20vcG9zdD91cmw9Jmx0Oz9waHAgdGhlX3Blcm1hbGluaygpOz8mZ3Q7JmFtcDt0aXRsZT0mbHQ7P3BocCB0aGVfdGl0bGUoKTs/Jmd0Ow==">Add to delicious</a>

Share on technorati

<a rel="external nofollow" target="_blank" href="https://zmingcx.com/wp-content/themes/begin/go.php?url=aHR0cDovL3RlY2hub3JhdGkuY29tL2ZhdmVzP3N1Yj1hZGRmYXZidG4mYW1wO2FkZD0mbHQ7P3BocCB0aGVfcGVybWFsaW5rKCk7PyZndDs=">Share on technorati</a>

Tweet this

<a rel="external nofollow" target="_blank" href="https://zmingcx.com/wp-content/themes/begin/go.php?url=aHR0cDovL3R3aXR0ZXIuY29tL2hvbWU/c3RhdHVzPUN1cnJlbnRseSByZWFkaW5nICZsdDs/cGhwIHRoZV9wZXJtYWxpbmsoKTsgPyZndDs=">Tweet this</a>

Delicious Stumbleupon Digg

大熊wordpress凭借多年的wordpress企业主题制作经验,坚持以“为用户而生的wordpress主题”为宗旨,累计为2000多家客户提供品质wordpress建站服务,得到了客户的一致好评。我们一直用心对待每一个客户,我们坚信:“善待客户,将会成为终身客户”。大熊wordpress能坚持多年,是因为我们一直诚信。我们明码标价(wordpress做网站需要多少钱),从不忽悠任何客户,我们的报价宗旨:“拒绝暴利,只保留合理的利润”。如果您有网站建设、网站改版、网站维护等方面的需求,请立即咨询右侧在线客服或拨打咨询热线:18324743309,我们会详细为你一一解答你心中的疑难。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

相关文章

写给所有做网站的朋友的一封信

写给所有做网站的朋友的一封信

现在就开始执行“1+N”互联网推广和没有开始执行的人,一两天看不出任何区别; 一两个月看来差异也是微乎其微的;但在2-5年的长远时间来看的时候,你的高质量询盘不断增加,你的互联网资产已经建立完成,对手已经很难匹敌,现在你看到这段文字的时候就是最好的开始,现在就是最好的时候,马上开始“1+N”体系的整体互联网推广吧,我们和你一起,开创互联网大未来!

点击查看详情

准备开启WordPress网站建设推广?

我们相信高端漂亮的网站不应该是昂贵的,这就是wordpress对每个人都是免费的原因
wordpress建站免费入门,并提供价格合理的wordpress建站套餐。