• 29/02/2016 • 7 phút đọc • 12 lượt xem

Tạo trang chỉnh sửa bài viết WordPress không dùng Plugin

Việt Lâm Coder
Việt Lâm Coder
Senior Fullstack & System Architect • Hotline: 0944.71.4545

Chào các bạn, ở 2 bài trước Mình đã giúp các Bạn tự tạo Trang Đăng bài và Trang quản lý bài cho thành viên, Tiếp theo mình sẽ giúp các bạn tạo trang sửa bài viết của thành viên đã đăng lên.

Tạo trang chỉnh sửa bài viết WordPress không dùng Plugin

Đầu tiên bạn cần tạo file sua-bai.php

Trong file này bạn cần có các nội dung sau:

– Kiểm tra thành viên đã được đăng nhập hay chưa, nếu chưa thì hiển thị khung đăng nhập


<?php
/*
Template Name: Sửa bài
*/
?>
<?php if(is_user_logged_in()) {
$user_id = get_current_user_id();
$current_user = wp_get_current_user();
$vnkings = $current_user->user_level;
if($vnkings <= 2) { $vnstatus = "pending"; } else { $vnstatus = "publish"; }
?>
// form Sửa bài
<?php } else { ?>
<div class="formdangnhap">
<?php wp_login_form(); ?>
</div>
<?php } ?>


– Thêm Form sửa bài viết (form mình đang sử dụng cấu trúc của Boostrap để các bạn tùy biến)

<?php $idvnkings = addslashes( $_GET['id'] ); ?>
<form id="new_post" class="form-horizontal" method="post" action="" enctype="multipart/form-data">
<div class="form-group vnking_pd col-sm-12 col-md-6">
<label for="post_title">Tiêu đề</label>
<input type="text" name="post_title" value="<?php echo get_the_title($idvnkings) ;?>" class="form-control" placeholder="Tiêu đề">
</div>

<div class="form-group vnking_pd pd_0">
<label for="post_content">Nội Dung</label>
<?php
$post = get_post( $idvnkings, OBJECT, 'edit' );
$content = $post->post_content;
wp_editor( $content, 'userpostcontent', array( 'textarea_name' => 'post_content' ));?>
</div>
<div class="form-group vnking_pd col-md-6">
<?php
$cats = get_the_category( $idvnkings);
$selected = 0;
if( $cats ) {
$selected = $cats[0]->term_id;
}
?>
<label for="post_content">Danh mục</label>
<?php
wp_dropdown_categories( array(
'orderby' => 'title',
'hide_empty' => false,
'id' => 'Posts_Picture_category',
'class' => 'form-control',
'name' => 'post_category',
'selected' => $selected
) );
?>
</div>
<div class="form-group vnking_pd col-md-6">
<label for="post_tags">Từ khóa</label>
<input type="text" name="post_tags" value="<?php echo $tagslist; ?>" class="form-control" placeholder="Từ khóa">
</div>

<div style="clear:both;"></div>
<div class="form-group">
<?php
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($idvnkings) );
?>
<p><img style="max-width:300px; display:block;" id="output_avatar" src="<?php echo $feat_image;?>"/></p>

<script>
var loadFile = function(event) {
var output = document.getElementById('output_avatar');
output.src = URL.createObjectURL(event.target.files[0]);
$('#output_avatar').addClass('active-avatar');
};
</script>
<span class="btn btn-default btn-file">Hình ảnh bài viết <input class="input-file" accept="image/*" name="file" type="file" class="file" /> </span>
</div>
<input type="hidden" name="add_new_post" value="post" />
<?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>
<div class="form-group">
<div class="col-sm-12" style="padding-left:0;">
<button type="submit" class="btn btn-primary">Sửa Bài</button>
</div>
</div>
</form>



Giải thích đoạn code

  • $idvnkings = addslashes($_GET[‘id’]) : Bạn hãy để ý đường dẫn khi click vào sửa bài ở trang quản lý bài viết sẽ có dạng : domain/sua-bai.html?id=60 vậy với đoạn code trên bạn sẽ lấy được id bài viết cần sửa

  • $post = get_post() : Lấy thông tin bài viết

  • $content = $post->post_content : Lấy nội dung bài viết

  • wp_editor() : Khung viết bài của wordpress

  • $feat_image : Lấy ảnh đại diện của bài viết

  • $tagslist; : Lấy Tags bài viết

  • wp_nonce_field() : Bảo mật cho form bài viết, giúp chứng thực sự hoạt động của người dùng nếu form đăng bài gửi đi


– Xử lý dữ liệu khi ấn vào sửa bài viết

<?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' )) {
if (isset($_POST['post_title'])) {
$post_title = $_POST['post_title'];
}
if (isset($_POST['post_content'])) {
$post_content = $_POST['post_content'];
}
else {
echo 'Please enter the content';
}
if (isset ($_POST['post_category'])) {
$post_category = $_POST['post_category'];
} else {
$post_category = 1;
}
if (isset($_POST['post_tags'])) {
$post_tags = $_POST['post_tags'];
}

$post = array(
'ID' => $idvnkings,
'post_title' => wp_strip_all_tags($post_title),
'post_content' => $post_content,
'post_category' => array($post_category),
'tags_input' => $post_tags,
'post_type' => 'post',
'post_status' => $vnstatus2,
);
$lovendpost_id_edit = wp_insert_post($post);

if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$lovendpost_id_edit);
}
}
echo '<div class="alert alert-success"><strong>Sửa bài Thành Công!</strong> <a href="'. get_permalink($idvnkings). '"> Xem Bài!</a></div>';
} ?>



Vậy tổng kết lại ta sẽ có 1 file sua-bai.php như sau:

<?php
/*
Template Name: Sửa bài
*/
?>

<div class="vnkings_form col-md-12">
<?php if(is_user_logged_in()) { ?>
<?php
$idvnkings = addslashes( $_GET['id'] );
$post_tags = wp_get_post_tags($idvnkings); $tagsarray = array();
$vnstatus2 = get_post_status($idvnkings);
foreach ($post_tags as $tag) {
$tagsarray[] = $tag->name;
}
$tagslist = implode( ', ', $tagsarray );
?>
<?php
$current_user = wp_get_current_user(); $userid = $current_user->ID; $curpost = get_post( $idvnkings );
$userlevel = $current_user->user_level;
//has permission?
$lovenduser = $curpost->post_author;
if ($userid == $lovenduser || $userlevel > 2 ) { ?>
<?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' )) {
if (isset($_POST['post_title'])) {
$post_title = $_POST['post_title'];
}
if (isset($_POST['post_content'])) {
$post_content = $_POST['post_content'];
}
else {
echo 'Please enter the content';
}
if (isset ($_POST['post_category'])) {
$post_category = $_POST['post_category'];
} else {
$post_category = 1;
}
if (isset($_POST['post_tags'])) {
$post_tags = $_POST['post_tags'];
}

$post = array(
'ID' => $idvnkings,
'post_title' => wp_strip_all_tags($post_title),
'post_content' => $post_content,
'post_category' => array($post_category),
'tags_input' => $post_tags,
'post_type' => 'post',
'post_status' => $vnstatus2,
);
$lovendpost_id_edit = wp_insert_post($post);

if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$lovendpost_id_edit);
}
}
echo '<div class="alert alert-success"><strong>Sửa bài Thành Công!</strong> <a href="'. get_permalink($idvnkings). '"> Xem Bài!</a></div>';
} ?>
<div id="postBox">
<form id="new_post" class="form-horizontal" method="post" action="" enctype="multipart/form-data">
<div class="form-group vnking_pd col-sm-12 col-md-6">
<label for="post_title">Tiêu đề</label>
<input type="text" name="post_title" value="<?php echo get_the_title($idvnkings) ;?>" class="form-control" placeholder="Tiêu đề">
</div>

<div class="form-group vnking_pd pd_0">
<label for="post_content">Nội Dung</label>
<?php
$post = get_post( $idvnkings, OBJECT, 'edit' );
$content = $post->post_content;
wp_editor( $content, 'userpostcontent', array( 'textarea_name' => 'post_content' ));?>
</div>
<div class="form-group vnking_pd col-md-6">
<?php
$cats = get_the_category( $idvnkings);
$selected = 0;
if( $cats ) {
$selected = $cats[0]->term_id;
}
?>
<label for="post_content">Danh mục</label>
<?php
wp_dropdown_categories( array(
'orderby' => 'title',
'hide_empty' => false,
'id' => 'Posts_Picture_category',
'class' => 'form-control',
'name' => 'post_category',
'selected' => $selected
) );
?>
</div>
<div class="form-group vnking_pd col-md-6">
<label for="post_tags">Từ khóa</label>
<input type="text" name="post_tags" value="<?php echo $tagslist; ?>" class="form-control" placeholder="Từ khóa">
</div>

<div style="clear:both;"></div>
<div class="form-group">
<?php
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($idvnkings) );
?>
<p><img style="max-width:300px; display:block;" id="output_avatar" src="<?php echo $feat_image;?>"/></p>

<script>
var loadFile = function(event) {
var output = document.getElementById('output_avatar');
output.src = URL.createObjectURL(event.target.files[0]);
$('#output_avatar').addClass('active-avatar');
};
</script>
<span class="btn btn-default btn-file">Hình ảnh bài viết <input class="input-file" accept="image/*" name="file" type="file" class="file" /> </span>
</div>
<input type="hidden" name="add_new_post" value="post" />
<?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>
<div class="form-group">
<div class="col-sm-12" style="padding-left:0;">
<button type="submit" class="btn btn-primary">Sửa Bài</button>
</div>
</div>
</form>
</div>
<?php } else { ?>
<div class="alert alert-warning"><strong>Bạn</strong> không có quyền Sửa bài viết này!</div>
<?php }?>
<?php } else { ?>
<div class="formdangnhap">
<div class="alert alert-warning"><strong>Bạn</strong> cần đăng nhập để sửa bài!</div>
<?php wp_login_form(); ?>
</div>
<?php } ?>
</div>



Trong quá trình thực hiện nếu bạn chưa hiểu hoặc khó thực hiện bạn có thể gửi câu hỏi ở bên dưới khung bình luận, mình sẽ cùng bạn hiểu rõ về nó!

Chúc các bạn thành công!

Nguồn : wordpress.vnkings.com

Việt Lâm Coder

Việt Lâm Coder

Tác giả bài viết và chuyên gia quản trị website. Nếu bạn gặp khó khăn trong quá trình thực hiện hoặc có nhu cầu thiết kế website, lập trình web app Laravel, hãy liên hệ ngay với tôi qua Hotline / Zalo: 0944.71.4545.

☕ Mời Tác Giả Ly Cà Phê Ấm Lòng

Nếu bài viết này giúp ích cho công việc của bạn, hãy tiếp thêm động lực cho tác giả duy trì kho tri thức bằng một ly cà phê ấm lòng nhé!

Mã QR ủng hộ tác giả
Ngân hàng TMCP Quân Đội (MB Bank)TONG VIET LAM

Có Thể Bạn Quan Tâm

Cách Mở Tab Ẩn Danh Trên Safari MacBook Đơn Giản

Cách mở tab ẩn danh trên Safari MacBook sẽ giúp cho người dùng có thể bảo vệ quyền riêng tư và duyệt web một cách an toà...

Hướng dẫn 5 cách tắt update Windows 11 vĩnh viễn chi tiết nhất

Mặc định Windows 11 sẽ được tự động cập nhật trong nền. Tuy nhiên nếu vì lý do nào đó mà bạn không muốn nhận các bản...

Hướng dẫn trỏ file hosts cho domain trên hệ điều hành Windows

– Làm cách nào để 1 website có thể hoạt động trên Share hosting, VPS, Server mà không cần cấu hình các record DNS cho do...

Kích hoạt Cloudflare Turnstile trong Contact Form 7 chống spam

Cloudflare Turnstile là giải pháp xác thực không dùng CAPTCHA giúp bảo vệ website WordPress khỏi spam một cách nhẹ nhàng...

Cách Sử Dụng DeepSeek R1 Miễn Phí Trong Visual Studio Code Với Cline?

Hãy đối mặt với thực tế: Các trợ lý lập trình AI như GitHub Copilot thì tuyệt vời, nhưng chi phí đăng ký của chúng có th...

Gmail API – Tất cả những gì bạn cần biết - 2025

Nếu bạn đang tìm cách tích hợp Gmail vào các ứng dụng của riêng mình thì Gmail API chính là thứ bạn cần! Gmail là một lự...

Hướng dẫn tạo màn hình desktop ảo bằng Task View trên Surface Windows 11

Việt Lâm Coder sẽ hướng dẫn tạo lập nhiều màn hình desktop ảo bằng Task View trên Surface Windows 11 để sắp xếp các tác...

How to Transfer PuTTY Sessions To Another Windows Machine

his is an user contributed article. PuTTY is a terminal emulator application which can act as a client for the SSH, T...

Hướng dẫn cách kiểm tra cổng đang mở (Check open port) trên linux

Với nhiều năm kinh nghiệm hỗ trợ Khách hàng của Tenten, chúng tôi nhận thấy việc thường xuyên theo dõi kiểm tra hoạt độn...

Kiểm tra tất cả các port mà Cyber Panel đang cần có được mở hay không ?

Để kiểm tra tất cả các port cùng một lúc, bạn có thể sử dụng lệnh: netstat -tulpn | grep -E ':(8090|80|443|21|40110|401...

Hướng dẫn cài đặt KeyHelp Panel

Tóm tắt về KeyHelp Bạn đã có phần cứng tốt nhất cho các dự án Internet của mình nhưng việc quản lý phức tạp, hiệu suất...

Tổng hợp danh sách Control Panel VPS free tốt nhất hiện nay

Control Panel VPS free cung cấp một lựa chọn tuyệt vời cho những người dùng muốn quản lý VPS một cách dễ dàng và hiệ...