Trang đăng bài cho thành viên trong wordpress không cần plugin

Tạo một trang đăng bài mới cho thành viên trên website chạy nên tảng wordpress của bạn là điều nên làm vì sẽ giúp cho trang web của bạn trông chuyên nghiệp hơn. Người dùng không cần phải mắc công vào trang dashboard wordpress rắc rối với đủ chức năng mà những người không chuyên sẽ cảm thấy phức tạp và đôi khi làm hoài không xong.

Với một một thành viên chỉ cần đăng bài thì họ chỉ cần cơ bản cho một bài đăng mới là tiều đề bài đăng, nội dung bài đăng, hình ảnh đại diện và một vài thứ linh tinh nho nhỏ nữa.
Với đoạn code dưới đây sẽ giúp bạn tạo một trang đăng bài mới trên wordpress cho thành viên mà không cần dùng đến plugin.

bạn tạo một file có đuôi .php trong thư theme của bạn ví dụ như dangbai.php và chép đoạn code dưới đây vào đó.
<?php
/*
 Template Name: Đăng bài
 */
 
if (!is_user_logged_in()) {
    wp_redirect( '/dang-nhap');
    exit;
}

get_header();
$user_id = get_current_user_id();
$current_user = wp_get_current_user();
$phungnghidinh =  $current_user->user_level;
if($phungnghidinh <= 2) { $pndstatus = "pending"; } else { $pndstatus = "publish"; }
?>
    
<main id="primary" class="site-main">
    <div class="container">
        <h2 class="category-title"><i class="fa fa-pencil-square-o"></i> Đăng Bài Viết Mới</h2>
        <div class="main-left">
            <div class="new-post-box">
                
                <form id="new_post" class="form-horizontal" method="post" action="" enctype="multipart/form-data" >
                    <div class="form-group">
                        <label>Tiêu đề</label>
                        <input type="text" name="post_title" class="form-control" >
                    </div>
                    <div class="form-group">
                        <label>Nội dung</label>
                        <div class="new-post-content">
                            <?php $post_obj = $wp_query->get_queried_object(); wp_editor( $post_obj->post_content, 'userpostcontent', array( 'textarea_name' => 'post_content' ));?>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Ảnh đại diện</label>
                        <div class="attachment-media-view">
                    <button type="button" id="image-btn" class="button-add-media">Set featured image</button>
                        <div id="action-btn" class="actions"></div>
                        </div>
                        <input id="image-url" type="hidden" name="image_url" />

                        <script>
                            // JavaScript to launch media uploader, should be enqueued in a separate file
                            jQuery(document).ready(function($){
                              var mediaUploader;
                              $('#image-btn').click(function(e){
                                e.preventDefault();
                                // If the uploader object has already been created, reopen the dialog
                                  if (mediaUploader) {
                                  mediaUploader.open();
                                  return;
                                }
                                // Extend the wp.media object
                                mediaUploader = wp.media.frames.file_frame = wp.media({
                                  title: 'Featured image',
                                  button: {
                                  text: 'Set featured image'
                                }, multiple: false });
                            
                                // When a file is selected, grab the URL and set it as the text field's value
                                mediaUploader.on('select', function() {
                                  attachment = mediaUploader.state().get('selection').first().toJSON();
                                  $('#image-url').val(attachment.url);
                                  $('#image-btn').html('<img id="preview-img" src="' + attachment.url + '"/>');
                                  $('#action-btn').html('<button type="button" id="remove-btn" class="button">Remove image</button>');
                                });
                                // Open the uploader dialog
                                mediaUploader.open();
                              });
                              //remove image
                              $('#remove-btn').live('click', (function () {
                                    $('#image-btn').html("Set featured image");
                                    $('#image-url').val('');
                                    $('#remove-btn').remove();
                                }));
                            });
                        </script>
                    </div>
                    <div class="form-group">
                        <label for="post_content">Danh mục</label>
                        <div>
                            <?php $categories = wp_dropdown_categories("echo=0&hide_empty=0&selected=0");
                                preg_match_all('/\s*<option class="(\S*)" value="(\S*)">(.*)<\/option>\s*/', $categories, $matches, PREG_SET_ORDER);
                                echo "<select id='post_category' class='form-control' name='post_category'>";
                                foreach ($matches as $match){
                                echo "<option value='{$match[2]}'>{$match[3]}</option>";
                                }
                                echo "</select>\n";
                            ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Từ khóa</label>
                        <input type="text" name="post_tags" class="form-control">
                    </div>
                    <div class="form-group">
            <label for="comment_status">
            <input type="checkbox" name="comment_status" id="comment_status" value="close" />
            <?php _e( 'Tắt chức năng comment', 'pndinh-comment' )?>
            </label>
                    </div>
                    <div class="form-group">
                        <label>Trang thái bài viết
                            <div class="post-status">
                                <input type="radio" name="post_status" value="publish" checked>
                                <span for="male">Publish</span>
                                <input type="radio" name="post_status" value="draft">
                                <span for="draft">Draft</span>
                            </div>
                        </label>
                    </div>
                    <input type="hidden" name="add_new_post" value="post" />
                    <?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>
                    <button type="submit" class="btn-submit">Đăng Bài</button>
                </form>
            </div>
        </div>
        <div class="main-right">
            <div class="sidebar">
                <?php get_sidebar(); ?>
            </div>
        </div>
    </div>
</main>

<?php if( $_SERVER['REQUEST_METHOD'] == 'POST' && !empty( $_POST['add_new_post'] ) && current_user_can('level_0') && isset( $_POST['post_nonce_field'] ) && wp_verify_nonce( $_POST['post_nonce_field'], 'post_nonce' )) {
    $post_title         =   $_POST['post_title'];
    $post_content       =   $_POST['post_content'];
    $post_category      =   $_POST['post_category'];
    $post_tags          =   $_POST['post_tags'];
    $imageURL           =   $_POST['image_url'];
    $comment_status     =   $_POST['comment_status'];
    $post_status        =   $_POST['post_status'];
    
    if(!empty($post_title) && !empty($post_content) && !empty($imageURL)){
        $post = array(
            'post_title'        =>  wp_strip_all_tags($post_title),
            'post_content'      =>  $post_content,
            'post_category'     =>  array($post_category),
            'tags_input'        =>  $post_tags,
            'comment_status'    =>  $comment_status,
            'post_status'       =>  $post_status,
            'post_type'         =>  'post',
        );
        $phungnghidinh_post_id = wp_insert_post($post);

        require_once(ABSPATH . "wp-admin" . '/includes/file.php');

        $imageId = attachment_url_to_postid($imageURL);
        update_post_meta($phungnghidinh_post_id, '_thumbnail_id', $imageId); 

        echo '<script language="javascript">';
        echo 'alert("Bài của bạn đã được đang thành công")';
        echo '</script>';

    }else{
        echo '<script language="javascript">';
        echo 'alert("Một bài đăng cần phải có đầy đủ tiêu đề, nội dung và hình đại diện")';
        echo '</script>';

    }
}

get_footer(); ?>
Để cho trang đăng bài mới cho thành viên có thể hiển thị trên website thì bạn vào trong phần page của dashboard tạo một trang mới và đặt tiêu đê "đăng bài" (hoặc gì tùy bạn), nội dung của trang bạn bỏ trống. Rồi đưa chuọt vào khung bên phải và kéo xuống phần Page Attributes và chọn "Đăng bài" trong ô template rồi publish cái trang đó lên và để đường link vào đâu tùy bạn muốn.

Rồi thêm một chút css vào cho nó trông đẹp hơn

.new-post-box,.edit-post-box{background:#fff;}
.post-status{margin-top:10px;margin-left:20px;}
.post-draft{color:#dc3232;}
.post-pendding{color:#fcb900;}
.form-group{margin-bottom:15px;}
.new-post-box h2, .edit-post-box h2{
    margin:0;
    margin-bottom: 25px;
    color:#2583d1;
}
.new-post-box h2:after, .edit-post-box h2:after {
    display: block;
    content: "";
    height: 2px;
    background: none repeat scroll 0% 0% #dfe0e4 !important;
}
.new-post-box select,.edit-post-box select{
    margin-top:10px;
}
.new-post-box h2:after{width:240px;}
.edit-post-box h2:after{width:170px;}
.new-post-box button, .edit-post-box button{font-size:15px;}
.new-post-box label, .edit-post-box label{margin-right:10px;font-weight:bold;}
.new-post-box span, .edit-post-box span {font-weight:normal;margin-right:15px;}
.new-post-content{margin:10px 0;}
.new-post-thumb{width:100px;height:100px;border:1px solid #ccc;margin:0;}
.new-post-thumb img{width:100px;height:100px;object-fit:cover}
.customize-control{display:inline-block;}
.attachment-media-view .button-add-media{
    cursor: pointer;
    background-color: #edeff0;
    color: #32373c;
    width: 200px;
    height:100px;
    position: relative;
    text-align: center;
    cursor: default;
    border: 1px dashed #b4b9be;
    box-sizing: border-box;
    line-height: 1.6;
    padding:0;
    margin-top:10px;
}
.attachment-media-view .button-add-media:hover{background-color:#fbfbfc;cursor:pointer;}
.attachment-media-view .button-add-media:focus{background-color:#fbfbfc;border-color:#007cba;border-style:solid;box-shadow:0 0 0 1px #007cba;outline:2px solid transparent}
.attachment-media-view img{width:100%;height:100%;}
#remove-btn{
    color: #0071a1;
    border-color: #0071a1;
    background: #f3f5f6;
    vertical-align: top;
    margin-top:10px;
}

Đăng nhận xét (0)
Mới hơn Cũ hơn