Use PHP + AJAX to allow WordPress to dynamically load the article's tutorial _ php instance

Source: Internet
Author: User
This article mainly introduces how to use PHP + AJAX to allow WordPress to dynamically load articles, that is, you do not need to manually refresh the browser page to display the loaded articles. For more information, see Why dynamic Article loading?

1. Quickly display pages to visitors
The article contains a large amount of text and multimedia resources (such as images, videos, and music). loading the content takes a lot of time. if there are a lot of articles on your page, visitors will feel impatient when they find that the page has not been loaded for a long time. this is the main purpose of dynamic Article loading.

2. List articles
Make the articles on the page a list to reduce the space occupied by the page. Visitors can easily move to the bottom of the page to increase the chance of the old articles being clicked. in addition, you can place more articles on the page without worrying about the page being too long.

Why not load articles dynamically?

1. unfriendly to search engines
Search engine optimization aims to display as many valuable things as possible to search crawlers, including the latest article content. only the title Article allows crawlers to only know this article but not the article's focus. The content of the article output using JavaScript may not be crawled or analyzed. these are not good for SEO.
Later I found that if your website has a fixed Article type and does not show too many articles on the article list page after graduation, the effect would not be great.

2. added the number of requests
Although we fold the article, we usually try to show the previous articles to the visitor. This is user-friendly, but we need to increase the number of requests and the number of database accesses.
Later, I selectively showed part of the article content, not through asynchronous loading. That is to say, this problem can be solved through simple modifications.

3. Some plug-ins are invalid
Because custom methods are required to capture articles. If no special processing is added, some WordPress plug-ins may become invalid.
It can be solved through special processing, which will be mentioned in later articles.

Dynamic Article Loading Design Ideas

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

2. Add the expand/collapse button to the article
Click the button. If the content of the article is not loaded, load and expand the content of the article.
Click the button. If the content of the article has been loaded, expand/collapse the content of the article.

3. Load the article content
Send the Article id to the background, find and format the corresponding article content in the database, and return the response displayed on the page.

JavaScript code analysis

1. Find all articles on the page

/When the document is loaded, traverse all elements matching the document jQuery (document ). ready (function () {jQuery ('p. post '). each (function () {// if the corresponding position of the element is the article ID var id = jQuery (this ). attr ('id'); if (/^ post \-[0-9] + $ /. test (id) {// Add a expand/collapse button for each article ...}});});

2. Add the expand/collapse button to the article

Toggle. toggle (function () {// expand // if the content of the article is empty, load the content of the article if (jQuery ('#' + id + '. content '). text () = ''){...} // display the article content and switch the button style jQuery ('#' + id + '. content '). slideDown (); jQuery (this ). removeClass ('collapse '). addClass ('expand');}, function () {// hide the article content, and switch the button style jQuery ('#' + id + '. content '). slideUp (); jQuery (this ). removeClass ('expand '). addClass ('collapse'); // append the button to the front of the article title }). prependTo (jQuery ('#' + id + 'h2 '));

3. Load the article content

// Obtain the document IDvar postId = id. slice (5); // use AJAX to obtain and process the document content jQuery. ajax ({type: 'get', url :'? Action = load_post & id = '+ postId, cache: false, ype: 'html', contentType: 'application/json; charset = UTF-8 '// display the loading information before obtaining the returned content. beforeSend: function (data) {loadPostContent (id ,'

Loading...

');} // The content of the article is obtained successfully. The content of the article is updated. success: function (data) {loadPostContent (id, data);} // An error occurred while obtaining the content of the article, error message displayed: error: function (data) {loadPostContent (id ,'

Oops, failed to load data.

');}});

Background Processing
Handling ideas

There are two parameters that are passed from the front-end to the backend. One is the action ID, which is used to determine the interface used, and the other is the Article ID, which is used to obtain the corresponding content of the article.

Next 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 the link text for "view full text" if (null ===$ more_link_text) $ more_link_text = _ ('(more ...) '); // The returned content $ output = ''; // the flag of the More tag $ hasTeaser = false; // if the password is required, if no processed information is found in the Cookie, the query form if (post_password_required ($ post) {$ output = get_the_password_form (); return $ output;} is returned ;} // if the requested Article segment is larger than the maximum page (that is, the article segment does not exist), if ($ page> count ($ pages )) $ page = count ($ pages); // the content of the article is the Article fragment in the last page $ content = $ pages [$ page-1]; // if the text contains More tags, if you want to cut the article and output the "view full text" link, redefine the article content and mark 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 disconnected and there is no paging requirement, if (false! = Strpos ($ post-> post_content ,'
 ')&&((! $ Multipage) | ($ page = 1) $ stripteaser = 1; // obtain the first part of the article content. If there is Read more and cut-off processing in an independent article, the article content is blank $ teaser = $ content [0]; if ($ more) & ($ stripteaser) & ($ hasTeaser) $ teaser = ''; $ output. = $ teaser; // if the article is divided into multiple clips, splice the second part in the independent article. The Link "read full text" is displayed in the abstract. 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_link_text); $ output = force_balance_tags ($ output) ;}} if ($ preview) // preview fix for javascript bug with foreign ages $ output = preg_replace_callback ('/\ % u ([0-9A-F] {4})/', create_function ('$ Match ', 'Return "&#". base_convert ($ match [1], 16, 10 ). ";"; '), $ output); // return the article content return $ preview ;}

You can think like this: as long as some input parameters are satisfied, some unnecessary ones are removed, some replaceable ones are replaced, and the page return is changed to the output, which is an interface for outputting the article content.

Solution

If we do not consider entering the password, paging, and other functions for the moment, because the More and cut-off functions should not exist in the content of the expanded article, the response processing can become very simple. we have to do the following:
1. Interface corresponding to the action
2. Get the content of a specified article
3. format the article content
4. Return the article content

It is useless to say more, directly add the code, and add comments:

Function load_post () {// if the action ID is load_post and the input parameter must exist, then, execute the response method if ($ _ GET ['action'] = 'Load _ Post' & $ _ GET ['id']! = '') {$ Id = $ _ GET [" id "]; $ output =''; // GET the article object global $ wpdb, $ post; $ post = $ wpdb-> get_row ($ wpdb-> prepare ("SELECT * FROM $ wpdb-> posts where id = % d LIMIT 1", $ id )); // if the specified ID already exists, format it if ($ post) {$ content = $ post-> post_content; $ output = balanceTags ($ content ); $ output = wpautop ($ output);} // print the content of the article and interrupt the subsequent processing 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.