Tutorial _php instance of using Php+ajax to let WordPress dynamically load articles

Source: Internet
Author: User
Why load articles dynamically?

1. Quickly show the page to visitors
The article is very tolerant of a lot of text and multimedia resources (such as: pictures, videos, music), loading these content takes a lot of time. If you have a large number of articles on your page, you will feel impatient when visitors find that the page has not been loaded for a long time. This is the main purpose of the dynamic loading of articles.

2. Make a list of articles
Make the article on the page become a list, reduce the space occupied by the page, visitors can easily move to the bottom of the page, improve the chance of the old article being clicked. And you can put more articles on the page without worrying about the page being too long.

Why not load articles dynamically?

1. Unfriendly to search engines
The goal of SEO is to show as much value as possible to search crawlers, including the latest article content. Only the title of the article let the crawler only know this article and do not know its article focus, the use of JavaScript output article content may not be able to be crawled and analyzed. These are not good for SEO.
Later found that if your site has a fixed article type, no graduation on the article List page shows too much article content, indicating little impact.

2. Increased number of requests
Although the article is folded up, we will generally find ways to show visitors the previous articles. This is friendly to the user, but increases the number of requests and the number of database accesses.
Later I chose to display some of the content of the article, and not by the way of asynchronous loading, that is, the problem can be solved by simple modification.

3. Some plugins fail
Because you need custom methods to crawl articles, if you do not add special processing, it is likely to make some WordPress plug-ins invalid.
can be resolved by special treatment, later in the article will be mentioned.

The design idea of dynamic loading article

1. Find all articles on the page
Add an expand/collapse button for each article

2. Add an expand/collapse button to an article
Click the button if the article content is not loaded, load and expand the article content.
Click the button to expand/collapse the article content if the article content is already loaded.

3. Load article content
Send the ID of the article to the background, find the appropriate article content in the database and format it, and return the response to the page.

JavaScript Processing Code Analysis

1. Find all articles on the page

/Iterate through all the elements of the matching article when the document is loaded JQuery (document). Ready (function () {jquery (' div.post '). Every (function () {///If the element corresponds to a location that is the article ID var id = jQuery (this). attr (' id '); if (/^post\-[0-9]+$/.test (ID)) {  //Add an expand/collapse button for each article ...  });});
2. Add an expand/collapse button to an article
Toggle.toggle (function () {//expand//If the article content is empty, load the article content if (JQuery (' # ' + ID + '. Content '). Text () = = ") {...}//Display the contents of the article and cut Change button style jQuery (' # ' + ID + '. Content '). Slidedown (); jquery (This). Removeclass (' collapse '). addclass (' expand ');},function () {//collapse//Hide article contents and toggle button style jQuery (' # ' + ID + '). Conte NT '). Slideup (); jquery (This). Removeclass (' expand '). addclass (' collapse ');//Append the button to the front of the article title}). Prependto (JQuery (' # ' + ID + ' H2 '));

3. Load article content

Get article Idvar PostID = Id.slice (5);//use AJAX to get and process the contents of the article Jquery.ajax ({type: '     get ', url:     '? action=load_post&id = ' + PostID, cache:    false, DataType:  ' html ', ContentType: ' Application/json; charset=utf-8 '//To display loading information before the return content is obtained. Beforesend:function (data) {loadpostcontent (ID, '

Loading ...

');} Get the content of the article successfully, update the article content, success: function (data) {loadpostcontent (ID, data);}//Get article content failed, display error prompt, Error: function ( Data) {loadpostcontent (ID, '

Oops, failed to load data.

');}});

Background processing
Processing ideas

There are two parameters from the foreground to the background, one is the action ID, which determines the interface used, and the other is the ID of the article, which is used to obtain the corresponding content of the article.

Let's analyze the Get_the_content method of wp-includes/post-template.php.

function Get_the_content ($more _link_text = null, $stripteaser = 0) {Global $id, $post, $more, $page, $pages, $multipage,  $preview;  Set "View full text" link copy if (null = = = $more _link_text) $more _link_text = __ (' (More ...) ');  return content $output = ';  The tag bit $hasTeaser = False if the label is present; If the article requires a password and the processed information is not found in the Cookie, return the view form that asks for the password if (post_password_required ($post)) {$output = Get_the_password_for M (); return $output;  }//The requested article fragment corresponds to a page that is larger than the maximum number of pages (that is, the article fragment does not exist), then the article fragment if ($page > Count ($pages)) $page = count ($pages) is returned; Article content is the last page of the article Fragment $content = $pages [$page-1]; If you have more tags in the text that require you to cut off the article and output the "View full text" link, redefine the content of the article, marking if the more tags exist if (preg_match ('/
 /', $content, $matches)) {$content = explode ($matches [0], $content, 2), if (!empty ($matches [1]) &&!empty ($more  _link_text)) $more _link_text = Strip_tags (Wp_kses_no_null (Trim ($matches [1])); $hasTeaser = true;  } else {$content = array ($content);} If the article is cut off and there are no paging requirements, if (False!== Strpos ($post->post_content, '
 ') && ((! $multipage) | | ($page ==1)))  ) $stripteaser = 1; Get the first part of the article content; If there is Read more and cut-off processing in the stand-alone article, then the article content is empty $teaser = $content [0]; if ($more) && ($stripteaser) && ($hasTeaser)) $teaser = ';  $output. = $teaser; If the article is divided into multiple fragments, the second part is stitched up in a separate article, and the "Read full text" link is displayed in the summary content if (count ($content) > 1) {if ($more) {$output. = '' . $content [1]; } else {if (! empty ($more _link_text)) $output. = Apply_filters (' The_content_more_link ', ' $more _link_text ', $more _li  Nk_text); $output = Force_balance_tags ($output); }} if ($preview)//preview fix for JavaScript bugs with foreign languages $output = Preg_replace_callback ('/\%u ([0-9a -F]{4})/', create_function (' $match ', ' return '). Base_convert ($match [1], 16, 10).  ";"; '), $output); Return the article to $preview;}
You can think of it this way: just meet some incoming parameters, remove some unnecessary, replace some replaceable, change the page back to output, is an interface to output the content of the article.

Processing methods

If we do not consider the input password, paging and other functions; In addition, because the more and the cut-off function should not exist in the expanded article content, the response processing can become very simple. Here are just a few things we're going to do:
1. Make an action-corresponding interface
2. Get the content of the specified article
3. Formatting the content of the article
4. Return to article content

Needless to say, directly on the code, add comments:

function Load_post () {//If the action ID is load_post and an incoming mandatory parameter exists, then the response method is executed if ($_get[' action '] = = ' Load_post ' && $_ge t[' id ']! = ') {$id = $_get["id"]; $output = ';  Get Article Object global $wpdb, $post; $post = $wpdb->get_row ($wpdb->prepare ("select * from $wpdb->posts WHERE ID =%d LIMIT 1", $id));  If an article with the specified ID exists, he is formatted with the IF ($post) {  $content = $post->post_content;  $output = Balancetags ($content);  $output = Wpautop ($output); }  //Print the contents of the article and interrupt the subsequent processing of the Echo $output; Die ();}} Add the interface to init add_action (' init ', ' load_post ');
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.