Add Widget After Content – Hiển thị bất cứ thứ gì bạn muốn như các bài viết liên quan, quảng cáo..vv
Ở bài trước mình có viết cách thêm một custom widget với tất cả những theme không có sẵn Add Widget Before Content. Bài viết này sẽ hướng dẫn làm thế nào để Add Widget After Content .
Đăng ký một Widget area
Đầu tiên chúng ta đăng ký một class_exists lớp này có nhiệm vụ kiểm tra xem lớp đã tồn tại hay chưa. Bạn sẽ cần phải thêm code vào file functions.php theme của bạn.
if ( !class_exists( 'AddWidgetAfterContent' ) ) { // php this }
Tiếp theo chúng ta hãy đăng ký một Widget area và hook nó vào đầu nội dung của post, page. Sử dụng add_action ‘widgets_init’ và add_filter ‘the_content’ chúng ta có code.
// Add Widget After content In Any WordPress Theme. if ( !class_exists( 'AddWidgetAfterContent' ) ) { class AddWidgetAfterContent { function __construct() { add_action( 'widgets_init', array( $this,'after_widgets_init' ) ); add_filter( 'the_content', array( $this,'insert_after_content') ); } function after_widgets_init() { $args = array( 'name' => 'Widget After Content ', 'id' => 'widget_after_content', 'description' => __( 'This is the widgets area after the content.', 'longviet' ), 'before_widget' => '<div class="awac-wrapper">', 'after_widget' => '</div>', 'before_title' => '<h4 class="widget-title">', 'after_title' => '</h4>' ); register_sidebar( apply_filters( 'awac_sidebar_arguments', $args ) ); } public function insert_after_content( $content ) { if ( is_singular( array( 'post', 'page' ) ) && is_active_sidebar( 'widget_after_content' ) && is_main_query() ) { $awac_content = $this->get_after_content(); $content.= apply_filters('awac_content', $awac_content ); } return $content; } public function get_after_content() { ob_start(); dynamic_sidebar( 'widget_after_content' ); $sidebar = ob_get_contents(); ob_end_clean(); return $sidebar; } } new AddWidgetAfterContent(); }
Code trên hiển thị Widget area vào đầu nội dung post, page. Nếu bạn muốn nó chỉ hiển thị trên Post hoặc Page hãy chỉnh sửa dòng 23.
Lời kết
Thêm một Widget After Content thật đơn giản phải không các bạn, bây giờ hãy đến khu vực Widget để thêm bất cứ thứ gì bạn muốn.
Tôi hy vọng bạn tìm thấy hướng dẫn này hữu ích. Nếu vậy, hãy xem xét chia sẻ nó với khán giả của bạn!