Thứ Ba, 20 tháng 9, 2016

Short code tự thêm bài liên quan trong giữa bài viết

Ở các trang báo bạn có thể thấy họ thường có chức năng hiển thị các bài viết liên quan đến bài đó ở ngay đầu hoặc giữa bài, đây là câu hỏi mà mình đã nhận được từ nhiều bạn có nhu cầu làm chức năng giống như vậy.
Bài liên quan ngay giữa nội dung như báo điện tử
Bài liên quan ngay giữa nội dung như báo điện tử
Về vấn đề này bạn hoàn toàn dư sức làm bằng thủ công vì nó sẽ chính xác hơn, nhưng nếu bạn cần nó làm tự động với độ chính xác thấp hơn thì có thể tham khảo bài này.

I. Cách thức

Để làm được chức năng này, chúng ta sẽ cần một code với 3 chức năng chính như sau:
  1. Hiển thị bài viết liên quan (liên quan theo taxonomy như tag, category, custom taxonomy).
  2. Code xác định được vị trí cần chèn. Cụ thể là chúng ta sẽ đếm số dòng văn bản trong nội dung dựa theo thẻ <p> trong mã HTML.
  3. Và cuối cùng là chúng ta sẽ chèn code 1 vào phần 2.
Về vấn đề số 1, thì bạn không cần code làm chi cho nó mệt mà mình khuyến khích bạn sử dụng plugin Related Posts by Taxonomy vì nó có hỗ trợ shortcode và nhiều tùy chọn khác trong shortcode để bạn có thể ứng dụng được nhiều trường hợp hơn. Do đó, hãy cài plugin này vào trước khi làm.
Do đó về phần viết code, ta chỉ viết code đếm số dòng và code chèn shortcode của plugin bài liên quan kia vào thôi.

II. Code đếm số dòng

Sở dĩ chúng ta cần đếm số dòng trong văn bản là vì ta sẽ dựa vào đó để gọi code chèn shortcode vào vị trí thích hợp. Trong bộ soạn thảo mặc định của WordPress, mỗi khi bạn xuống hàng nó sẽ tự định nghĩa hàng đó là một cặp thẻ <p>. Vì vậy ở đây chúng ta sẽ có code để đếm hệ thống hiểu rằng chúng ta đang nhắm tới các thẻ <p> mà đếm.
Chèn code sau vào file functions.php mà không cần sửa gì.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
// Code đếm số dòng trong văn bản
function count_paragraph( $insertion, $paragraph_id, $content ) {
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
        foreach ($paragraphs as $index => $paragraph) {
                if ( trim( $paragraph ) ) {
                        $paragraphs[$index] .= $closing_p;
                }
                if ( $paragraph_id == $index + 1 ) {
                        $paragraphs[$index] .= $insertion;
                }
        }
        return implode( '', $paragraphs );
}
Bây giờ chúng ta đã có hàm count_paragraph() làm nhiệm vụ xác định được các thẻ <p> trong văn bản với cấu trúc sử dụng như sau:
01
count_paragraph($nội-dung-cần-chèn, $số-dòng-cần-chèn-vào, $content);
Trong đó, $content chính là nội dung của bài viết để chúng ta sử dụng tính năng add_filter.

III. Chèn bài liên quan vào nội dung

Bây giờ việc cuối cùng của chúng ta là sử dụng cái hàm count_paragraph() đã tạo ở trên và kết hợp với filter trong WordPress để chèn bài liên quan vào. Chèn code sau vào file functions.php:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
//Chèn bài liên quan vào giữa nội dung
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
        $related_posts= do_shortcode('[related_posts_by_tax title=""]');
        if ( is_single() ) {
                return count_paragraph( $related_posts, 1, $content );
        }
        return $content;
}
Trong code trên, ta có biến $related_posts sẽ chứa hàm thực thi shortcode của plugin mà bạn đã cài. Trong plugin này có rất nhiều tham số mà bạn có thể tham khảo tại đây.
Kế tiếp là bạn để ý đoạn sau:
01
02
03
if ( is_single() ) {
        return count_paragraph( $related_posts, 1, $content );
}
Đoạn này ta có hàm is_single() để kiểm tra xem trang đó có phải là trang single hay không để tránh tình trạng nó hiển thị ra ngoài trang chủ làm mất tinh tế.
Kế tiếp là đoạn return count_paragraph( $related_posts, 1, $content ), bạn thấy số 1 chứ? Số 1 ở đây nghĩa là nó sẽ tự chèn shortcode bài liên quan vào sau dòng số 1 trong văn bản. Bạn có thể thay số một thành số khác tùy thích. Số càng lớn thì bài liên quan sẽ hiển thị càng sâu xuống dưới, giá trị nhỏ nhất là 1.
Ok, bây giờ toàn bộ code ta có trong bài này là như sau: (chèn toàn bộ vào file functions.php)
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Code đếm số dòng trong văn bản
function count_paragraph( $insertion, $paragraph_id, $content ) {
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
        foreach ($paragraphs as $index => $paragraph) {
                if ( trim( $paragraph ) ) {
                        $paragraphs[$index] .= $closing_p;
                }
                if ( $paragraph_id == $index + 1 ) {
                        $paragraphs[$index] .= $insertion;
                }
        }
        return implode( '', $paragraphs );
}
//Chèn bài liên quan vào giữa nội dung
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
        $related_posts= do_shortcode('[related_posts_by_tax title=""]');
        if ( is_single() ) {
                return count_paragraph( $related_posts, 1, $content );
        }
        return $content;
}
Kết quả ta có:
Bài liên quan ngay giữa nội dung như báo điện tử
Bài liên quan ngay giữa nội dung như báo điện tử
Nếu bạn cần cho nó đẹp hoặc muốn viết CSS riêng cho nó thì thay:
01
$related_posts= do_shortcode('[related_posts_by_tax title=""]');
Thành
01
$related_posts= "<div class='meta-related'>".do_shortcode('[related_posts_by_tax title=""]')."</div>";
Sau đó viết CSS cho class .meta-related mà thôi, ví dụ chèn đoạn sau vào file style.css
01
02
03
04
05
meta-related {
  font-size: 13px;
  line-height: 1.4em;
  font-weight: bold;
}
Xong rồi đấy. Theme nào cũng làm như nhau nhé.

Chủ Nhật, 18 tháng 9, 2016

Lỗi "What do I do when I receive an Internal Server Error?" - Wordpress

Thông báo lỗi web dưới dạng
"Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, support@supportwebsite.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

Apache/1.3.33 Server at mydomain.com Port 80"


Cause

This error can be caused by a variety of issues but is most likely caused by a corrupt .htaccess file. Check to see if there is an .htaccess file in the directory where the error is being generated or any directory above in the tree. If so, temporarily rename the .htaccess file and refresh the page. If the error does not reappear, the .htaccess file is the issue. Repair the file or leave it disabled.
If you encounter further issues with the renamed .htaccess file, revert its name, and try restoring it from a backup.
Most of the time .htaccess issues are caused by trying to overwrite PHP settings, being uploaded in binary format or permissions issues.

Resolution

Be sure to upload .htaccess files in ASCII mode
Set the permissions to 644, which makes it usable by the server, but prevents it from being read from a browser.
If you are trying to make changes to PHP settings, be sure to make changes to your PHP initialization file.

Thứ Năm, 15 tháng 9, 2016

File wp-config.php

<?php
/**
 * The base configuration for WordPress
 *
 * The wp-config.php creation script uses this file during the
 * installation. You don't have to use the web site, you can
 * copy this file to "wp-config.php" and fill in the values.
 *
 * This file contains the following configurations:
 *
 * * MySQL settings
 * * Secret keys
 * * Database table prefix
 * * ABSPATH
 *
 * @link https://codex.wordpress.org/Editing_wp-config.php
 *
 * @package WordPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'ten database o day');

/** MySQL database username */
define('DB_USER', 'username o day ');

/** MySQL database password */
define('DB_PASSWORD', 'dien pass vao day');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');


define( 'WP_MEMORY_LIMIT', '256M' );

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         'put your unique phrase here');
define('SECURE_AUTH_KEY',  'put your unique phrase here');
define('LOGGED_IN_KEY',    'put your unique phrase here');
define('NONCE_KEY',        'put your unique phrase here');
define('AUTH_SALT',        'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT',   'put your unique phrase here');
define('NONCE_SALT',       'put your unique phrase here');

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix  = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the Codex.
 *
 * @link https://codex.wordpress.org/Debugging_in_WordPress
 */
define('WP_DEBUG', false);

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');

Thứ Hai, 12 tháng 9, 2016

file .htaccess

php_value max_execution_time 3000

php_value max_input_vars 3000

<IfModule mod_headers.c>
  <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css|css|js)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress