WordPress code to implement related articles

WordPress has a lot of plug-ins to achieve the relevant features of the article, the advantages of plug-in configuration is simple, but the speed of the site may cause some small impact, so many people still prefer to use code to achieve the required functions, but then again, Code to achieve there are shortcomings, is the configuration of complex, do not understand the code completely puzzled or can only copy someone else’s code, not as good as plug-ins.
Here I have compiled several code to achieve the relevant article method, which will detail the role of the various parts of the code, and how to customize the function you want, we hope to help, what questions can be published in this article Comments, I will reply to you in time. Before you start, note that all of the following methods output the HTML code format are in the form that you can modify as needed:
<ul id = “xxx”>
<li> * <a title=”>> Curseys 1″ rel=”bookmark” href=” paper> Link 1″> Article Title 1 </a> </ li>
<li> * <a title=” pages of paper2″ rel=”bookmark” href=” paper> link 2″> article title 2 </a> </ li>

</ ul>

Method 1: Label related
First get all the labels of the article, and then get the n articles under these tags, then the n article is related to the article on the article. Now you can see the WordPress related article plugins are used this method. The following is the implementation of the code:
<ul id = “tags_related”>
<? php
$ post_tags = wp_get_post_tags ($ post-> ID);
if ($ post_tags) {
foreach ($ post_tags as $ tag)
// Get the tag list
$ tag_list []. = $ tag-> term_id;
// Randomly get a label in the tag list
$ post_tag = $ tag_list [mt_rand (0, count ($ tag_list) – 1)];
// The method uses the query_posts () function to call the related article, the following is the parameter list
$ args = array (
‘tag__in’ => array ($ post_tag),
‘category__not_in’ => array (NULL), // not included in the category ID
‘post__not_in’ => array ($ post-> ID),
‘showposts’ => 6, // show the number of related articles
‘caller_get_posts’ => 1
query_posts ($ args);
if (have_posts ()):
while (have_posts ()): the_post (); update_post_caches ($ posts);?>
<li> * <a href=”<?php the_permalink();;> “rel =” bookmark “title =” <? php the_title_attribute ();?> “> <? php the_title ();?> </ a > </ li>
<? php endwhile; else:?>
<li> * No related articles </ li>
<? php endif; wp_reset_query ();}?>
</ ul>
Instructions for use: “does not include the classification of ID” refers to the article does not show the classification of the article, the peer NULL into the article can be classified ID, multiple ID comma separated by commas. Because the limit here only shows 6 related articles, so no matter to the query_posts () parameter tag__in how many values, are only show a label under the six articles, unless the first label has 1, the second label has 2, the third has 3. The The The The The So if this article has multiple tags, then we take the method is to randomly get a tag id, assigned to the tag__in this parameter, access to the six articles under the label.

Method 2: Classification related
The method is to obtain the article by the classification id, and then get the article under the category, to achieve the purpose of access to relevant articles.
<ul id = “cat_related”>
<? php
$ cats = wp_get_post_categories ($ post-> ID);
if ($ cats) {
$ cat = get_category ($ cats [0]);
$ first_cat = $ cat-> cat_ID;
$ args = array (
‘category__in’ => array ($ first_cat),
‘post__not_in’ => array ($ post-> ID),
‘showposts’ => 6,
‘caller_get_posts’ => 1);
query_posts ($ args);
if (have_posts ()):
while (have_posts ()): the_post (); update_post_caches ($ posts);?>
<li> * <a href=”<?php the_permalink(); ?> “rel =” bookmark “title =” <? php the_title_attribute ();
?> “> <? php the_title ();?> </a> </ li>
<? php endwhile; else:?>
<li> * No related articles </ li>
<? php endif; wp_reset_query ();}?>
</ ul>

wordpress latest, most comment and random log function trinity one

The latest log, the heat log, the random log these three functions in the function is very similar, nothing more than a sort of different, the latest log is sorted by the release time, hot comment log is sorted by the number of comments, random log is random Sorting. So I simply put these three functions into one, on the one hand to reduce the functionality.php code redundancy, on the other hand also facilitate their own management.
Copy the following function into functions.php in the WordPress theme directory:
function get_posts ($ orderby = ”, $ plusmsg = ”) {
$ get_posts = query_posts (‘posts_per_page = 10 & caller_get_posts = 1 & orderby =’. $ orderby);
foreach ($ get_posts as $ get_post) {
$ output = ”;
$ post_date = mysql2date ($ y month d day, $ get_post-> post_date);
$ commentcount = ‘(‘. $ get_post-> comment_count. ‘comments’);
$ post_title = htmlspecialchars (stripslashes ($ get_post-> post_title));
$ permalink = get_permalink ($ get_post-> ID);
$ output. = ‘<li> <a href=”‘. $permalink.'” title=”‘.$post_title.'”>’. $ post_title. ‘</a>’. $$ plusmsg. ‘</ li;
echo ‘<ul>’. $ output. ‘</ ul>’;
wp_reset_query ();
The calling method is as follows:
<? php
// the latest log
get_posts ($ orderby = ‘date’, $ plusmsg = ‘post_date’);
// hot comment log
get_posts ($ orderby = ‘comment_count’, $ plusmsg = ‘commentcount’);
// random log
get_posts ($ orderby = ‘rand’, $ plusmsg = ‘post_date’);
You can see that they share a function of the three, but only different parameters Bale, such as the title, the latest, hot evaluation, random log function Trinity is completed.
Here I introduce the latest WordPress, hot comment, random log three-in-one function set in the time range of 30 days, the effect of the site on the sidebar of the log on it, all in 30 days within.
First put the following function in the WordPress theme folder in the functions.php:
function filter_where ($ where = ”) {
$ where. = “AND post_date>”. date (‘Y-m-d’, strtotime (‘- 30 days’)).
return $ where;
function some_posts ($ orderby = ”, $ plusmsg = ”, $ limit = 10) {
add_filter (‘posts_where’, ‘filter_where’);
$ some_posts = query_posts (‘posts_per_page =’. $ limit. ‘& caller_get_posts = 1 & orderby =’. $ orderby);
foreach ($ some_posts as $ some_post) {
$ output = ”;
$ post_date = mysql2date ($ y month d day), $ some_post-> post_date);
$ commentcount = ‘(‘. $ some_post-> comment_count. ‘comments’);
$ post_title = htmlspecialchars (stripslashes ($ some_post-> post_title));
$ permalink = get_permalink ($ some_post-> ID);
$ output. = ‘<li> <a href=”‘. $permalink.'” title=”‘.$post_title.'”>’. $ post_title. ‘</a>’. $$ plusmsg. ‘</ li;
echo $ output;
wp_reset_query ();
You can see the second line of 30 refers to the last 30 days, you can also modify the time according to your own needs. As for the call and upgrade before the same, the following is just more than the last one $ limit parameters:
<? php
// the latest log
some_posts ($ orderby = ‘date’, $ plusmsg = ‘post_date’, 10);
// hot comment log
some_posts ($ orderby = ‘comment_count’, $ plusmsg = ‘commentcount’, 10);
// random log
some_posts ($ orderby = ‘rand’, $ plusmsg = ‘post_date’, 10);
OK, then I want to click on the highest ranking is also changed to 30 days ranking, so often to patronize the user should be more reasonable it, or it seems to look at a few, the title to see rotten.

Useful SQL query in WordPress

WordPress stores all of its information snippets (including articles, pages, comments, blog links, plugin settings, etc.) in the MySQL database. Although WordPress users can edit the above information snippet through the site background editing. to a certain degree.
But assuming that you have hundreds of articles on the WordPress site, and you need to change the whole station range, then edit from the background is a bit time-consuming effort, and the probability of mistakes will increase. The best way is to enter the WordPress MySQL database to perform the necessary queries (changes). Through MySQL can quickly complete the above tasks, for you to save more time.
The following is to introduce some time-saving WordPress SQL query method.

The WordPress database stores all the articles you’ve posted carefully, all the comments from your readers, and all the personalizations you’ve made to your site. So, no matter how confident you are, please remember that you must back up the WordPress database in advance. You can back up the backup plugin.

Add a custom field for all articles and pages
This code can add a custom field to all articles and pages in the WordPress database. What you need to do is replace the ‘UniversalCutomField’ in the code with the text you want, and change the ‘MyValue’ to the desired value.
INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, ‘UniversalCustomField’
AS meta_key ‘MyValue AS meta_value FROM wp_posts
WHERE ID NOT IN (SELECT post_id FROM wp_postmeta WHERE meta_key = ‘UniversalCustomField’);
If you only need to add a custom field for the article, you can use the following code:
INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, ‘UniversalCustomField’
AS meta_key ‘MyValue AS meta_value
(SELECT post_id FROM wp_postmeta WHERE meta_key = ‘UniversalCustomField’)
“ AND post_type = ‘post’;
If you only need to add a custom field for the page, you can use the following code:
INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, ‘UniversalCustomField’
AS meta_key ‘MyValue AS meta_value
(SELECT post_id FROM wp_postmeta WHERE meta_key = ‘UniversalCustomField’)
AND `post_type` = ‘page’;

Delete the article meta data
When you install or remove the plug-in, the system stores the data through the article meta tag. Plug-in is deleted, the data will remain in the post_meta table, of course, then you no longer need these data, you can delete it. Remember to replace the ‘YourMetaKey’ in the code with the corresponding value you need before running the query.
DELETE FROM wp_postmeta WHERE meta_key = ‘YourMetaKey’;

Find useless tags
If you delete the old article in the WordPress database, the article will remain in the database and will appear in the tag list / tag cloud, as in the case of the previous plugin. The following query can help you find useless tags.
SELECT * From wp_terms wt
INNER JOIN wp_term_taxonomy wtt ON wt.term_id = wtt.term_id
WHERE wtt.taxonomy = ‘post_tag’ AND wtt.count = 0;

Batch delete spam comments
Execute the following SQL commands:
DELETE FROM wp_comments WHERE wp_comments.comment_approved = ‘spam’;

Bulk delete all unaudited comments
This SQL query will delete all unaudited comments on your site without affecting the comments that have been reviewed.
DELETE FROM wp_comments WHERE comment_approved = 0

No comment on earlier articles
Specifies that the value of comment_status is open, closed, or registered_only. Also need to set the date (modify the code in 2010-01-01):
UPDATE wp_posts SET comment_status = ‘closed’ WHERE post_date <‘2010-01-01’ AND post_status = ‘publish’;

Disable / activate trackback and pingback
Specifies that the value of comment_status is open, closed, or registered_only.
Activate pingbacks / trackbacks for all users:
UPDATE wp_posts SET ping_status = ‘open’;
Disable pingbacks / trackbacks for all users:
UPDATE wp_posts SET ping_status = ‘closed’;

Activate / deactivate Pingbacks & Trackbacks before a date
Specifies that the value of ping_status is open, closed, or registered_only. Also need to set the date (modify the code in 2010-01-01):
UPDATE wp_posts SET ping_status = ‘closed’ WHERE post_date <‘2010-01-01’ AND post_status = ‘publish’;

Delete comments for specific URLs
When you find a lot of spam comments with the same URL link, you can use the following query to delete these comments at once. % Means that all URLs containing the string within the “%” symbol will be deleted.
DELETE from wp_comments WHERE comment_author_url LIKE “% nastyspamurl%”;

Identify and remove articles from “X” days ago
Find all articles for “X” days (note that replace X with the corresponding value):
SELECT * FROM `wp_posts`
WHERE `post_type` = ‘post’
AND DATEDIFF (NOW (), `post_date`>> X

Remove all articles from “X” days ago:
DELETE FROM `wp_posts`
WHERE `post_type` = ‘post’
AND DATEDIFF (NOW (), `post_date`>> X

Remove unwanted short codes
When you decide not to use short code, they will not disappear automatically. You can use a simple SQL query command to remove all unwanted short codes. Replace “tweet” with the corresponding short code name:
UPDATE wp_post SET post_content = replace (post_content, ‘[tweet]’, ”);

Change the article to page
Still just through PHPMyAdmin run a SQL query can get:
UPDATE wp_posts SET post_type = ‘page’ WHERE post_type = ‘post’
Convert the page to article:
UPDATE wp_posts SET post_type = ‘post’ WHERE post_type = ‘page’

Change the author attribute on all articles
First, the author’s ID is retrieved by the following SQL command:
SELECT ID, display_name FROM wp_users;
After successfully getting the author’s new ID, insert the following command, remember to replace NEW_AUTHOR_ID with the new author ID, and replace the old author ID with OLD_AUTHOR_ID.
UPDATE wp_posts SET post_author = NEW_AUTHOR_ID WHERE post_author = OLD_AUTHOR_ID;

Batch delete article revision history
Article revision history can be very useful to save, it can be very annoying. You can manually delete the revision history, you can also use the SQL query to save their time.
DELETE FROM wp_posts WHERE post_type = “revision”;

Disable / activate all WordPress plugins
Activate a plug-in and found unable to log in WordPress management panel, and try the following query command, it will immediately disable all plug-ins, so you re-login.
UPDATE wp_options SET option_value = ‘a: 0: {}’ WHERE option_name = ‘active_plugins’;

Change the target URL for the WordPress site
After moving the WordPress blog (template file, upload content & database) from one server to another, then you need to tell WordPress your new blog address.
When using the following command, note that http://www.old-site.com is replaced by your original URL and http://www.new-site.com is replaced by a new URL.
First of all:
UPDATE wp_options
SET option_value = replace (option_value, ‘http://www.old-site.com’, ‘http://www.new-site.com’)
WHERE option_name = ‘home’ OR option_name = ‘siteurl’;
Then use the following command to change the URL in wp_posts:
UPDATE wp_posts SET guid = replace (guid, ‘http: //www.old-site.com’, ‘http: //www.new-site.com);
Finally, search the contents of the article to ensure that the new URL link is not confused with the original link:
UPDATE wp_posts
SET post_content = replace (post_content, ‘http://www.ancien-site.com’, ‘http://www.nouveau-site.com’);

Change the default user name Admin
Replace one of your YourNewUsername with a new username.
UPDATE wp_users SET user_login = ‘YourNewUsername’ WHERE user_login = ‘Admin’;

Manually reset the WordPress password
If you are the only author on your WordPress site and you have not modified the default username, you can use the following SQL query to reset the password (replace the PASSWORD with the new password):
UPDATE `wordpress`.`wp_users` SET` user_pass` = MD5 (‘PASSWORD’)
WHERE `wp_users`.`user_login` =` admin` LIMIT 1;

Search and replace article content
OriginalText replaced with replaced content, ReplacedText replaced with the target content:
UPDATE wp_posts SET `post_content`
= REPLACE (`post_content`,

Change the image URL
The following SQL command can help you modify the image path:
UPDATE wp_posts
SET post_content = REPLACE

WordPress only shows the friend links on homepage

Do seo optimization, links to the whole station link and just the home page link is very different. Will be decentralized. Many common wordpress templates are set links throughout the station, so we need to achieve wordpress only show links in the home page and need to toss the wordpress template.
Here for everyone to say that modify the wordpress link seo optimization techniques.

Method 1: Modify the theme source code
In the background to find the location of the link in the theme of the location, background – appearance – editor can be found. The general theme of the link is on the side (sidebar.php), also on the footer (footer.php), according to their own theme to find the link code: <? Php wp_list_bookmarks ();
After that, replace the following code:
<? php if (is_home ()) {?>
<? php wp_list_bookmarks ();?>
<? php}?>
Code explanation: is_home (); Description This code contains links only in the home page.
But I use this code to test, no effect, check the content page is still a link, always want to understand what is the problem? After asking the Supreme, wordpress a lot of people, and finally find a solution to the problem.
As long as the is_home (); before adding a wp_reset_query (); can be resolved, the perfect get.
The final code is as follows:
<? php wp_reset_query (); if (is_home ()) {?>
<? php wp_list_bookmarks ();?>
<? php}?>

Method 2: Plugin settings
1, plug-in name: Widget Logic in the background search installation start.
2, after the figure to speak, background settings. Fill in the following options is_home () &&! Is_paged () and then click Save on the set is completed

WordPress link settings map
3, some commonly used display instructions
is_home () home page
is_admin () administrator account
is_single () article page
is_page () page
is_404 () page can not find page
is_search () search results page
is_feed () subscription page
The is_category (5) only in the ID non-5 classification display
is_category () article classification page
is_tag () article tab
is_archive () archive page
The following explains the meaning of some symbols: || that or, && that and, that is not.

WordPress no plugin automatically displays thumbnails

Like toss to modify the wordpress theme friends, certainly encountered such a problem, would like to show thumbnails in the home page, there are plug-ins can be achieved, but not easy to operate and control, after all, the code is written, and today to share with you, No plug-in, pure code is how to achieve the first page of the article thumbnails, the method is very simple, even if you do not understand the code, according to the steps can also be. Of course, the thumbnail is selected in the article in the first picture, if the article does not contain pictures, show the default picture, so you have to set a default picture location.
Into the topic, start to add the first page thumbnail, simple 3 steps can be achieved:

The first step: find the use of the theme template function.php file in the <? Php and?> Add the following code:
function thumb_img ($ soContent) {
$ soImages = ‘~ <img [^ \>] * \ /> ~’;
preg_match_all ($ soImages, $ soContent, $ thePics);
$ allPics = count ($ thePics [0]);
if ($ allPics> 0) {
echo “<span id = ‘thumb’>”;
echo $ thePics [0] [0];
echo ‘</ span>’;
else {
echo “<span id = ‘thumb’>”;
echo “<img src = ‘”;
echo bloginfo (‘template_url’);
echo “/images/thumb.gif ‘> </ span>”;
This is a method of displaying thumbnails, automatically retrieving the first picture of the article, and if you do not show the current theme /images/thumb.gif so you should have this thumb.gif picture ready.

The second step: find the index.php file that is the first page file, find the_content (); or similar code before it add the following code:
thumb_img ($ post-> post_content);
This call the method just now, in fact, the thumbnail has been completed. But you see the effect must be very unexpected, the size of the picture should be no control, will be ugly.

Step 3: Add thumbnail style CSS code:
This is the cloud station used in the thumbnail style, you can make do with the use, and then modify it
#thumb {margin: 5px 15px 5px 5px; width: 145px; height: 120px; border: 3px solid #eee; float: left; overflow: hidden;}
#thumb img {max-height: 186px; max-width: 186px}

Well, so there is a thumbnail showing a kind of show it.

How does WordPress replace domainname?

Open a personal blog friends use WordPress a few, then it is inevitable that the replacement of space and domain name, because the author experienced a replacement space and domain name, the blog changed from AAA.com to BBB.com, so this article to share Replace the domain name better way.
WordPress we all know that the background needs to set the site’s default URL, if the direct replacement of the domain name, then use the new domain name is unable to login. There are many articles on the Internet, tell you can modify the MySQL database, or modify the WordPress wp-config.php file or function.php file, in fact, not so much trouble.
As long as the replacement before and after the domain name in their own hands, then the solution is very simple. First change the domain name before and after the analysis are resolved to the blog space, that is, so that the old and new domain name can correctly access the blog. To determine whether the old and new domain name can be properly accessed, in addition to their own local direct access to the two domain names can be properly accessed to the site, but also need to see other areas of domain name access is normal, because Telecom, China Unicom, there are different areas of DNS effective time is different of. At this time the station owners have a good tool, but the use of super ping (http://ping.chinaz.com), the old and new domain names were entered into the super ping, to see whether all over the ping .
If you determine the old and new domain names are parsed after the normal, you can change the domain name, and in a word called witness the miracle of the moment.
With the administrator login WordPress background, click Settings → General, inside the WordPress address (URL) and site address (URL) are modified to a new domain name, and then click Save Changes. Hey, ye quit, in fact, is a success, look at the browser’s address bar is not a new address? Log in with the administrator account, look at the settings → routine is not a new domain name? And then click on the home page to see if it is not a new domain name, if you enter the old domain name will not jump to the new domain name It is clear that the change is successful, is not very simple.
But because of the blog article in some of the links and picture address or use the old domain name, so also need to make some changes.
Login phpmyadmin, select your own database of the blog, and then click SQL, enter the following three lines of command:
UPDATE wp_posts SET post_content = replace (post_content, ‘AAA.com’, ‘BBB.com’);
UPDATE wp_comments SET comment_content = replace (comment_content, ‘AAA.com’, ‘BBB.com’);
UPDATE wp_comments SET comment_author_url = replace (comment_author_url, ‘AAA.com’, ‘BBB.com’);
And then click on the implementation, if there is no error, then the article and the comments will be replaced in all the addresses.
This time with a new address to visit it, the domain name to replace the perfect.

WordPress articles are automatically added at the bottom of the copyright notice and links

Now write a blog is not easy, but also copied or reproduced, so many bloggers at the bottom of the article will add copyright notice and links. Hope that some respect for the copyright of the Internet people can be reproduced in the time to leave a link and source. But if each article is manually added, then it will be very troublesome, and WordPress blog can be easily achieved automatically add copyright notice and links.
The original Liboseo is used directly in the article template in the article below to add the code, I use the WordPress official twentyten theme modified, so edit the theme of the loop-single.php, find the following code:
<div class = “entry-content”>
<? php the_content ();?>
<? php wp_link_pages (array (‘before’ => ‘<div class = “page-link”>’. __ (‘Pages:’, ‘twentyten’), ‘after’ => ‘</ div>’)) ;
</ div> <! – .entry-content ->
<? php the_content ();?>
Followed by the following code:
<copy> please specify from <a href=’http://www.cmsjzy.cn’> CMS concentration camp </a>, this article address: <a href=<?php the_permalink();;> ‘title = ‘<? php the_title ();?>’> <? php the_permalink ();?> </a>
Unless noted, CMS concentration camp articles are original, reproduced, please indicate the source and link! </ pre>
But out of the question, that is, if you install some wumii or Baidu share like plug-ins, then add the contents of the above can only be found in the absence of the following, rather than close to the article. Obviously this is not the effect we want.
After a variety of tests, and finally through the theme of the custom function to solve.
The method is very simple, because the reason we add the content can not be close to the article, because these plugins will be inserted into the contents of the_content (); function, and this function is WordPress program default function. If we modify the_content () function directly, then if you upgrade the WordPress program, it will be overwritten.
So I am through the theme of the functions.php file, in the bottom to add a custom function liboseo_content (), as follows:
function liboseo_content ($ more_link_text = null, $ stripteaser = 0) {
$ content = get_the_content ($ more_link_text, $ stripteaser);
$ content. = “<pre> reprint please specify from <a href=’http://www.cmsjzy.cn’> CMS concentration camp </a>,”;
$ content. = “URL: <a href='”.get_permalink($post, true).”‘ title='”.get_the_title($post_id).”‘>” .get_permalink ($ post, true). </a> “;
$ content. = “\ n unless noted, CMS concentration camp articles are original, reproduced please specify the source and link! </ pre>”;
$ content = apply_filters (‘the_content’, $ content);
$ content = str_replace (‘]]’, ‘]] & gt;’, $ content);
echo $ content;
And then the theme of the article template in the_content (); replaced with a custom function, such as my theme template file is loop-single.php, directly on the_content (); modified to liboseo_content (); into The
<div class = “entry-content”>
<? php liboseo_content ();?>
<? php wp_link_pages (array (‘before’ => ‘<div class = “page-link”>’. __ (‘Pages:’, ‘twentyten’), ‘after’ => ‘</ div>’)) ;
</ div> <! – .entry-content ->
To keep a look at it, is it a success? Before the change must be back up the original file, if possible, it is best to test the local good, and then modify the site.

WordPress blog batch delete all SPAM spam comments method

WordPress is a very popular mature free blog system. Now the network will produce a lot of spam every day (SPAM), many open the comments function WordPress blog every day can receive a large number of automatic submission by Bot, the water soldier for manual submission of spam comments. These spam comments are mainly based on the website link, which is a popular way to promote the network. These spam comments on the traffic big WordPress blog is a very helpless thing. There are some bloggers due to work for some time did not take care of the comments of the blog message, after a period of time back to find the blog was submitted a lot of SPAM spam comments.
We all know that in the WordPress management background can be selected in batches of 20 comments, and then delete or mark them as SPAM, but if there are thousands of pending comments this is not a way. What we need is a way to remove all spam comments in a way that can be a key, or more convenient. The study found a few can be more convenient to delete all the spam comments to be reviewed by the method to share with everyone.

Method One, use the WordPress plugin to remove all pending comments
We can download and install a Plugin plugin that can remove all Pending comments – Delete Pending Comments – WordPress plugin download address
After the installation of the wordpress background management comments (Comments) below you can see “Delete Pending Comments” (delete pending comments) link. Click on this link and will ask you to enter a word “I am sure I want to delete all pending comments and accessible this can not be undone” (I’m sure to delete all pending comments and know that deleted comments can not be restored) Make sure you want to delete all pending comments in bulk. Note that this is the comment that is pending review, not all comments, so the old comments will still be retained (including those that have been marked as SPAM spam comments will not be deleted).

Use the WordPress plugin to remove all pending comments
After typing this sentence, click the Delete Pending Comments button below to delete all pending comments in batches.

Method 2, use Akismet Smart Recognition to remove all spam comments
This method is more intelligent than the first method and is worth recommending. Akismet is a well-known anti-spam system on the WordPress blog system where blogs can use it to scan and remove all spam comments. Akismet is characterized by its ability to intelligently determine which comments are SPAM spam, which reviews are really written by people, and valuable blog comments (English station recognition rate is not higher). Akismet link address
To install Akismet first you need to get a WordPress API key. Click on the background after the installation is complete. Then you can see a check for the check for the Spam button at the Edit Comments section. Click this button, Akismet will automatically start scanning all the comments, and all the comments on the characteristics of spam comments classified as spam category. This is also the reason why this method is recommended, because Akismet will leave the real comment more intelligent than the first way to remove all pending comments.

Use Akismet Smart Recognition to remove all spam comments

Method 3, use phpMyAdmin into the MySql database to remove all spam comments
If you prefer to write a command, you can try this method. First login WordPress blog where the MySql database server, enter the WordPress database, through a SQL statement batch delete the database in addition to review all comments by commenting the record. Methods as below:
Log in WordPress where the MySql database, and then click on the right side of the SQL, copy and paste the following code into the large text box:
DELETE FROM wp_comments WHERE comment_approved = ‘0’
wp_comments is the comment where the data table name, if your table name needs to be changed to your table name, and then click the bottom right corner of the GO button. Use this method to remove all comments other than comments by review, including comments to be reviewed, marked as spam. Spam comments are useless, this can also effectively reduce the size of the database, played a clean up the purpose of the database.

Use phpMyAdmin to access the MySql database to remove all spam comments

Finally, sum up: the first method: all the comments to be reviewed are deleted, the old comments will be retained, but the real review of the same review was deleted. The second method, more intelligent, but the high recognition rate is not high I did not test (if you try to give feedback on the results to us). In the third, all the comments in the database that are not audited are deleted, leaving only the comments that were approved. Is not the world feel a lot of quiet?

WordPress theme to add google font

Google Web Fonts provide a secure and beautiful font service for your blog for free. By using Google Web Fonts, your blog does not have to upload any fonts to display fonts other than the usual “Arial”, “Verdana” fonts.
As we all know, website readability depends on its design and appearance. Web design plays the most important role in the font, the use of what kind of font is important to your site. For example, Arial / Helvetica (sans-serif), Verdana and Georgia are our commonly used web design fonts. These fonts provide a good readability, but if you want to use the new font, all you need to do is make sure that the viewer’s network device installs these fonts. This is difficult to determine. So you have to upload their own fonts to the server, and through CSS to be controlled. But now, there is a better free tool, that is, Google Web Fonts
Before you use the Google Web Fonts service, first understand the following two points:
Choosing too many fonts will slow down your blog loading speed, so you just have to choose what you have to use to avoid slowing down your visit.
If you can only choose the language you need, you will help prevent your page from becoming slow.
At present, the interface and preview language of Google Web Fonts are not English (without interfering with Chinese).
Google Web Fonts can visually display a variety of web fonts, like Serif, Sans-Serif, Display and Handwriting, you can also browse certain properties, such as script display font, width, tilt and thickness. All of these properties can be displayed in the side pane. When you choose the font you want, you can also intuitively preview the overall style such as words, sentences, paragraphs and so on.
Here is a simple tutorial to help you use Google Web Fonts faster and faster:
1. Click Google Web Fonts to enter the Google font service, select the font you want, and then click the “Add to collection” button in the lower right corner. Here we select the “Alike” font as an example font for the entire tutorial.

2. Click “Add to collection”, there will be a message at the bottom of the page “1 font family in your collection” and three buttons, “Choose”, “Review” and “Use.” Here we Select “Use”. That is to use.

3. It also requires setting the font. Select available styles, such as “bold, italic,” and so on. But only for certain specific fonts. Next, select the specific language character. Generate the code.

4. Next is the code department, Google fonts provide three application code, namely the standard mode “Standard (external stylesheet)”, export mode “@import method” and JS mode “JavaScript”. As needed, now you need the pattern, but here we recommend choosing the standard mode. Copy the code in step 3 and copy them to your theme header.php before </ head>.
5. Now add the font name to your theme’s css file. For example: You want to use google web Fonts in paragraph <p> as the default display font. css code directly write on the line:
p {
font-family: ‘Alike’, Arial;
This code will display the google font “Alike” in your blog paragraph, and if the font to be loaded encounters some temporary problems, it will appear as a “arial” font. Likewise, you can add a font style to other elements, such as “body” overall layout, links to “li” lists, and so on.

The WP-PostViews plug-in shows how to set the time for the popular article

Do not know for what reason, 1.30 after the WP-PostViews plugin canceled the original existence of the get_timespan_most_viewed function, which is also recently learned on the Internet, because recently have the mood to modify the theme, plug-in, find kid’s blog above this plugin provides small Tools in the sidebar display content is not how to change a few months, the reason is very simple, set up is the most browsing articles, more and more more and more, so I would like to modify the display settings, unfortunately the background is not related settings, although There is the nearest, but it seems that I am not the result.
Baidu for a while to know the original plug this function, and now there is no, but some people share the previous function on the Internet, so much simpler. Copy the following function to the wp-postviews.php file anywhere (of course, to the appropriate point of any place, do not put other functions in the middle ok).
function get_timespan_most_viewed ($ mode = ”, $ limit = 20, $ days = 1, $ display = true) {
global $ wpdb, $ post;
$ limit_date = current_time (‘timestamp’) – ($ days * 86400);
$ limit_date = date (“Y-m-d H: i: s”, $ limit_date);
$ where = ”;
$ temp = ”;
if (! empty ($ mode) && $ mode! = ‘both’) {
$ where = “post_type = ‘$ mode'”;
} else {
$ where = ‘1 = 1’;
$ most_viewed = $ wpdb-> get_results (“SELECT DISTINCT $ wpdb-> posts. *, (meta_value + 0) AS views FROM $ wpdb-> posts LEFT JOIN $ wpdb-> postmeta ON $ wpdb-> postmeta.post_id = $ “AND AND meta_keyword = ‘ideas’ AND post_password = ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ORDER BY views DESC LIMIT $ limit ‘);
if ($ most_viewed) {
foreach ($ most_viewed as $ post) {
$ post_title = get_the_title ();
$ post_views = intval ($ post-> views);
$ post_views = number_format ($ post_views);
$ temp. = “<li> <a href=\””.get_permalink().”\”> $ post_title </a> – $ post_views” .__ (‘views’, ‘wp-postviews’). < / li> “;
} else {
$ temp = ‘<li>’ .__ (‘N / A’, ‘wp-postviews’). ‘</ li>’. \ n “;
if ($ display) {
echo $ temp;
} else {
return $ temp;
Just put the above statement is still not work, although many blogs that can, may all think that write blog language? Although I can change, but the boy think that for those who do not understand why php novice, it is really harder and harder ah.
Here kid for everyone to sort out the next, for everyone to share.
case ‘least_viewed’:
get_least_viewed ($ mode, $ limit, $ chars);
Very simple, open the wp-postviews.php file in the ### Function: Display Least Viewed Page / Post or other functions above the above function, once again, the function to add location, but as far as possible with other business functions put together, Easy to analyze it! After the operation is the small tool options Statistics Type add get_timespan_most_viewed option, this directly in the wp-postviews.php file search Statistics Type, you can see
<$ php_e (‘Least Viewed’, ‘wp-postviews’);?> </ option>
Or the contents of other options, copy a line, paste to the top or below (of course, can also be the middle), and then the above statement least_viewed or other copy of the statement you change the value to get_timespan_most_viewed, so complete the background operation, But the current choice of this option is not displayed after the sidebar, because the output of the place to improve, the next step is also in the wp-postviews.php file operation, search class WP_Widget_PostViews, function widget function to find the switch statement, which should have Four turns, shaped like
case ‘least_viewed’:
get_least_viewed ($ mode, $ limit, $ chars);
Do not want to re-copy a copy of the location to the parallel, will least_viewed modified to get_timespan_most_viewed, so back to the first page refresh, the display should be a hot day, because the function is the default (the original function is the default 30 days, Set to 1 day), there is no option in the background, there is a need to modify the function of their own data can be.
In addition, the point is that the above provided get_timespan_most_viewed function is the old version of the function, does not support the current version of the output format, etc., where the kid and according to the new variable definition of the following functions, you can directly replace the above provided The get_timespan_most_viewed function is used, the function body is as follows
$ where = “post_type = ‘$ mode'”;
} else {
$ where = ‘1 = 1’;
$ most_viewed = $ wpdb-> get_results (“SELECT DISTINCT $ wpdb-> posts. *, (meta_value + 0) AS views FROM $ wpdb-> posts LEFT JOIN $ wpdb-> postmeta ON $ wpdb-> postmeta.post_id = $ “AND AND meta_keyword = ‘ideas’ AND post_password = ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ORDER BY views DESC LIMIT $ limit ‘);
if ($ most_viewed) {
foreach ($ most_viewed as $ post) {
$ post_views = intval ($ post-> views);
$ post_title = get_the_title ($ post);
if ($ chars> 0) {
$ post_title = snippet_text ($ post_title, $ chars);
$ post_excerpt = views_post_excerpt ($ post-> post_excerpt, $ post-> post_content, $ post-> post_password, $ chars);
$ temp = stripslashes ($ views_options [‘most_viewed_template’]);
$ temp = str_replace (“% VIEW_COUNT%”, number_format_i18n ($ post_views), $ temp);
$ temp = str_replace (“% POST_TITLE%”, $ post_title, $ temp);
$ temp = str_replace (“% POST_EXCERPT%”, $ post_excerpt, $ temp);
$ temp = str_replace (“% POST_CONTENT%”, $ post-> post_content, $ temp);
$ temp = str_replace (“% POST_URL%”, get_permalink ($ post), $ temp);
$ output. = $ temp;
} else {
$ output = ‘<li>’ .__ (‘N / A’, ‘wp-postviews’). ‘</ li>’. \ n “;
if ($ display) {
echo $ output;
} else {
return $ output;
As shown in the function parameters, set the number of days has been marked with the note, where is still no longer provide the option to set the panel, the need for friends can own toss, kid in the debugging time may be because the day visit is too low, set 1 day Can not achieve the desired display, set back to 30 days, we can set according to need.

WordPress comes with TinyMCE editor using the full version of the skills

Since the use of WordPress since I do not know how many background editing, from FCKEditor to CKeditor, and even some of the little-known CodeRenderUnmi and WLW, FE editor, etc., used to find some features really strong, but It is necessary to modify a lot of things with easy, and once WordPress or plug-in itself to upgrade their own, those who have to modify the things that must be re-set again, quite trouble; or some offline editor, copy to paste to Very bother. Up to now, I still feel that, wordpress template comes with the editor is the most powerful and practical!
Is the so-called “since the intensive, gradually in the absence of sword wins the sword of the territory,” put aside those exaggerated editor, back to WordPress comes with TinyMCE editor up, you know, WordPress itself is constantly strong, Every time the upgrade on the built-in editor changes are very practical, not only the integration of multimedia functions together, and gives the feeling is more and more neat, since we can see the official on the editor TinyMCE Attention to the degree. Now I will own the editor TinyMCE own way to paste out, all the code only need to write to the theme of the functions.php file, even if the future upgrade WordPress also do not need to repeat the operation.
Change the editor default view to HTML
As we all know, in the background of the new article, the editor will automatically jump to the “visual” view, for some often insert the code or WEB designers (I was ^ _ ^), may be more accustomed to using HTML view manually edit. Also, like CKEditor editing in the visual view has no <p> or <div> tag, but will automatically add to the HTML view, of course, this is CKEditor automatic settings nothing wrong, but in the future want to re-edit a published When the article will be a headache, because CKEditor will be self-contained to generate a lot of complicated or confusing code, keep the code clean and tidy is very inconvenient (of course, you want to make do with the actual display will not have a great change, but Will reduce the structure of the page).
Set the method: Add the following code to the theme’s functions.php file:
add_filter (‘wp_default_editor’, create_function (”, ‘return’ html “; ‘));
Add editor default content (visible in editor)
After the new article editor editor content is empty by default, some friends do is wordpress theme station, plug-in station or a simple download station, some standard formatted article will enter the “theme name”, “theme author” , “Download address” and other content, add the default content, the repetitive work later no longer, and everything is pre-defined. And if the article does not need to publish these pre-defined content, only need all-Delete ok, and will not be very troublesome.
To set the method: Add the following code to the subject functions.php file:
function insertPreContent ($ content) {
if (! is_feed () &&! is_home ()) {
$ content. = “<div class = ‘wpohome’>”;
$ content. = “<h4> CMS concentration camp </ h4>”;
$ content. = “The predefined content here is visible in the editor <a href=’http://www.cmsjzy.cn’> CMS concentration camp </a>”;
$ content. = “</ div>”;
return $ content;
add_filter (‘default_content’, ‘insertPreContent’);
Add editor default content (not visible when editing)
The content added by this method is automatically added at the end of the content when the article is published, invisible at the time of editing, used to add subscriptions, article copyright information, and so on.
To set the method: Add the following code to the subject functions.php file:
function insertFootNote ($ content) {
if (! is_feed () &&! is_home ()) {
$ content. = “<div class = ‘wpohome’>”;
$ content. = “<h4> CMS concentration camp </ h4>”;
$ content. = “The predefined content here is visible in the editor <a href=’http://www.cmsjzy.cn’> CMS concentration camp </a>”;
$ content. = “</ div>”;
return $ content;
add_filter (‘the_content’, ‘insertFootNote’);
Add more HTML tags (with caution)
This feature should be used with caution, because WordPress comes with the TinyMCE editor will filter out the default does not meet the XHTML 1.0 html tags, such as “br /”, “iframe” and so on. But do not rule out the case may also use these labels, so the method for the reference for you.
Add method: Paste the following code into the theme’s functions.php file:
function fb_change_mce_options ($ initArray) {
$ ext = ‘pre [id | name | class | style], iframe [align | longdesc |
name | width | height | frameborder | scrolling | marginheight |
margin? | src] ‘; // Note: The format is “label one [attribute one | attribute two], label two [attribute one | attribute two | attribute three]
if (isset ($ initArray [‘extended_valid_elements’])) {
$ initArray [‘extended_valid_elements’]. = ‘,’. $ ext;
} else {
$ initArray [‘extended_valid_elements’] = $ ext;
return $ initArray;
add_filter (‘tiny_mce_before_init’, ‘fb_change_mce_options’);

WordPress title title repeats is not conducive to SEO solution

In the use of Google administrator tools found when the wordpress blog list page repeat page 56, is certainly very detrimental to seo. We all know that wordpress paging calls the title tag in header.php, for which we can fix the problem by repeating the title of the title page on the title tab in the header.php on the title tag to join the paging page of the calling tag to tell the search engine this Is the two pages, and ultimately achieve the SEO effect.
Here, I mainly talk about the category, that is, the title of the catalog directory is repeated, other pages are similar.
Before we can add the page number, we can find this line of code in header.php:
<? php if (is_category ()) {?> <? php single_cat_title ();?> – <? bloginfo (‘name’);?> <? php}
At this point, if the category directory article goes beyond one page, we can see that all the category titles are duplicated, that is, “category directory title – blog title”, we can modify the following,
$ paged = get_query_var (‘paged’); if ($ paged> 1) printf ($ paged> 1) printf (‘paged’); ‘-% s page’, $ paged);?> <? Php}?>
This code means that the first page to obtain the number, if not the first page then add the page number, said the first few pages, through this method can effectively eliminate the page page repeat the title of the problem.
In order to achieve the classification of the title of the title “category directory title – blog title – page number”, in addition to the first page.
Similarly, if it is the home page, you can
($ paged> 1) printf (‘- the% s page’); </ p> </ p> </ p> </ p> </ p> <p> $ paged); <? php}?>
Other pages are also similar, just need to be
$ paged = get_query_var (‘paged’); if ($ paged> 1) printf (‘-% s page’, $ paged);
Add to the appropriate location can be.

WordPress will select the text forwarded to the microblogging method

Tencent news recently looked at, when inadvertently found that when I selected the news in the text, the upper right corner of the mouse will display a “broadcast to microblogging” button, click on the selected text will be forwarded to the microblogging The This is a very good user experience, if it can be introduced into the WordPress blog, it is not very good?
I also specifically to register a developer of Tencent microblogging open platform, when I began to read the development of the document, only to find his sister, Tencent official has launched a similar function of the application, called “Q-Share “, And then read some of the other information, the original has been written by the older generation of js page text selected to share Sina microblogging method, then I more effort, the combination of the two, the microblogging and Tencent microblogging two A button are added, and then the pain of the egg I put it translated into a jQuery method.
Effect, then you can see the site, and select any text, it will show two microblogging button in the upper right corner, click to try it.
Implementation of the method is also very simple, only two steps:
1, the introduction of jQuery, I believe most of the WordPress blog has been introduced jQuery, it can be a direct second step.
2, at the bottom of the page, or more precisely, in the introduction of the jQuery library behind the addition of such a JS, you can see the same effect and the site.
var miniBlogShare = function () {
// Specify the location in the node
$ (‘<img id = “imgSinaShare” class = “img_share” title = “will be selected content to share Sina microblogging” src = “http://www.cmsjzy.cn /2012/0203/1328255868614.gif” /> <img id = “imgQqShare” class = “img_share” title = “will be selected content to share to Tencent microblogging” src = “http://www.cmsjzy.cn /2012/0203/1328255868314.png” /> ‘). appendTo (‘body’);

// default style
$ (‘. img_share’). css ({
display: ‘none’,
position: ‘absolute’,
cursor: ‘pointer’

// Select the text
var funGetSelectTxt = function () {
var txt = ”;
if (document.selection) {
txt = document.selection.createRange (). text;
} else {
txt = document.getSelection ();
return txt.toString ();

// Select the microblog icon after selecting the text
$ (‘html, body’). mouseup (function (e) {
if (e.target.id == ‘imgSinaShare’ || e.target.id == ‘imgQqShare’) {
e = e || window.event;
var txt = funGetSelectTxt (),
sh = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0,
left = (e.clientX – 40 <0)? e.clientX + 20: e.clientX – 40,
top = (e.clientY – 40 <0)? e.clientY + sh + 20: e.clientY + sh – 40;
if (txt) {
$ (‘# imgSinaShare’). css ({
display: ‘inline’,
left: left,
top: top
$ (‘# imgQqShare’). css ({
display: ‘inline’,
left: left + 30,
top: top
} else {
$ (‘# imgSinaShare’). css (‘display’, ‘none’);
$ (‘# imgQqShare’). css (‘display’, ‘none’);

// click Sina Weibo
$ (‘# imgSinaShare’). click (function () {
var txt = funGetSelectTxt (), title = $ (‘title’). html ();
if (txt) {
window.open (‘http://v.t.sina.com.cn/share/share.php?title=’ + txt + ‘- reprinted from:’ + title + ‘& url =’ + window.location.href);

// click on Tencent microblogging
$ (‘# imgQqShare’). click (function () {
var txt = funGetSelectTxt (), title = $ (‘title’). html ();
if (txt) {
window.open (‘http://vtqq.com/share/share.php?title=’ + encodeURIComponent (txt + ‘- reprinted from:’ + title) + ‘& url =’ + window.location.href) ;
} ();
Note: This method is not only applicable to WordPress, JS is common, you can mount this JS to any website can get the same effect.

WordPress search engine crawling record code

Write a blog for some time, why the search engine is not included in your page? Want to know what spiders are “visiting” your site every day? As a wordpress user, it is necessary to know what spiders crawl every day to your website in order to understand the search engine spider crawling frequency, the site for targeted SEO optimization.
In fact, very simple, just add the following code, and then call the document code on the OK, is not it convenient? Let’s get started.
Before I also looked for a few spider crawling tools PHP version, the results are unsatisfactory. And most of these PHP programs to be installed, but also to add the spider crawl records to MYSQL, too much trouble. Then look for a simple spider crawler
1. First, create a robots.php file in the wordpress theme root and write the following:
<? php
function get_naps_bot ()
$ useragent = strtolower ($ _ SERVER [‘HTTP_USER_AGENT’]);
if (strpos ($ useragent, ‘googlebot’)! == false) {
return ‘Googlebot’;
if (strpos ($ useragent, ‘msnbot’)! == false) {
return ‘MSNbot’;
if (strpos ($ useragent, ‘slurp’)! == false) {
return ‘Yahoobot’;
if (strpos ($ useragent, ‘baiduspider’)! == false) {
return ‘Baiduspider’;
if (strpos ($ useragent, ‘sohu-search’)! == false) {
return ‘Sohubot’;
if (strpos ($ useragent, ‘lycos’)! == false) {
return ‘Lycos’;
if (strpos ($ useragent, ‘robozilla’)! == false) {
return ‘Robozilla’;
return false
function nowtime () {
$ date = gmdate (“Y-n-j H: i: s”, time () + 8 * 3600);
return $ date;
$ searchbot = get_naps_bot ();
if ($ searchbot) {
$ tlc_thispage = addslashes ($ _ SERVER [‘HTTP_USER_AGENT’]);
$ url = $ _ SERVER [‘HTTP_REFERER’];
$ file = “robotslogs.txt”;
$ time = nowtime ();
$ data = fopen ($ file, “a”);
fwrite ($ data, “Time: $ time robot: $ searchbot URL: $ tlc_thispagen”);
fclose ($ data);
Upload it in your theme directory.
2. In the appropriate location of Footer.php or header.php add the following code to call robots.php.
<? php include (‘robots.php’)?>
Program principle: through the spider identifier (such as Baiduspider, Googlebot) to judge, record the spider creep time, and generate the log file robotslogs.txt in the root directory.
Program Disadvantages: can not record the spider crawling the page, the function is relatively simple.

WordPress comments add input mailbox instantly display Gravatar avatar function

Gravatar is an abbreviation for Globally Recognized Avatar, a service launched by gravatar, meaning “Global Universal Avatar” (already wall). If you put your own avatar on Gravatar’s server, then in any message that supports Gravatar’s blog or message, just provide the email address associated with this avatar to show your Gravatar header.
New theme with this feature, it is not difficult to achieve, so posted to share under
1. Add the following code to the functions.php file and add the default avatar to the comment box.
add_filter (‘comment_form_top’, ‘show_gravatar’);
function show_gravatar () {
global $ current_user;
get_currentuserinfo ();
echo is_avatar ($ current_user-> user_email, 40); // 40 is the size of the avatar, step 4 is the same
2. Set the position of the avatar with CSS, which is fixed in the upper right corner.
#commentform {position: relative}
#commentform .avatar {position: absolute; top: 0; right: 20px}
3. Download http://pajhome.org.uk/crypt/md5/2.2/md5-min.js, save to the theme folder.
4. Rename the file just to gravatar.js, add the following code at the end of this file:
if (document.getElementById (“email”)) {
document.getElementById (“email”). onblur = function () {
if (/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\a-a- zA-Z0-9_-]{2,3} ) {1,2}) $ /. Test (this.value)) document.getElementById (“commentform”). GetElementsByTagName (“img”) [0] .src = “http://www.gravatar.com/avatar / “+ Hex_md5 (this.value) +”? D = mm & s = 40 “;
If you find the email input box, when the cursor focus out of the email input box, with the regular test input is the email format, if it is inserted before the picture address to the newly generated address.
5. Open footer.php, add the following code:
<? php if (is_singular () && comments_open ()) {?> // Judgment is not a separate post page and comments open
<script type = “text / javascript” src = “<? php bloginfo (‘template_url’);?> / js / gravatar.js”> </ script>
<? php}?>
Simple 5 steps, instant display Gravatar function on the complete realization.