Skip to content

Instantly share code, notes, and snippets.

@DavidPeralvarez
Created May 7, 2019 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidPeralvarez/81684444021ee785dc23a0e0d8d90740 to your computer and use it in GitHub Desktop.
Save DavidPeralvarez/81684444021ee785dc23a0e0d8d90740 to your computer and use it in GitHub Desktop.
Mejoramos nuestro plugin
<?php
/*
Plugin Name: Seguridad en Plugins
Description: Aprendiendo a hacer nuestros plugins más seguros
Text Domain: seguridad-plugins
Domain Path: /languages
*/
/**
* Añadimos un enlace para eliminar el post
* y un formulario para cambiar el título al
* final de su contenido
*/
add_filter( 'the_content', 'dp_sep_add_options' );
function dp_sep_add_options( $content ){
$new_content = $content;
if( is_single() && in_the_loop() && is_main_query() && current_user_can('edit_others_posts') ):
// http://cursodesarrolloplugins.local/?action=dp_sep_delete&post_id=8
$post_id = get_the_ID();
$url = add_query_arg( array(
'action' => 'dp_sep_delete',
'post_id' => $post_id,
'nonce' => wp_create_nonce('dp_sep_delete-'.$post_id),
), home_url() );
// Añadimos el enlace
$new_content .= '<a href="'.esc_url($url).'">'.esc_html__( 'Eliminar post', 'seguridad-plugins').'</a>';
// Añadimos el formulario
$new_content .=
'<form action="" method="post">'.
wp_nonce_field( 'dp_sep_update_title-'.$post_id, 'nonce' ).'
<input type="hidden" name="action" value="dp_sep_update_title">
<input type="hidden" name="post_id" value="'.esc_attr($post_id).'">
<input type="text" name="post_title" value="" placeholder="'.esc_attr__( 'Nuevo título', 'seguridad-plugins').'">
<input type="submit" value="'.esc_attr__( 'Cambiar', 'seguridad-plugins').'">
</form>';
endif;
return $new_content;
}
/**
* Recuperamos los parámetros de la URL y actuamos
* según el parámetro recibido
*/
add_action( 'init', 'dp_sep_delete_or_update_post' );
function dp_sep_delete_or_update_post(){
if( isset( $_REQUEST['action'] ) &&
isset( $_REQUEST['post_id'] ) &&
isset( $_REQUEST['nonce'] ) &&
current_user_can('edit_others_posts') &&
wp_verify_nonce( $_REQUEST['nonce'], $_REQUEST['action'].'-'.$_REQUEST['post_id']) &&
(absint($_REQUEST['post_id']) == $_REQUEST['post_id'])
):
$action = $_REQUEST['action'];
$post_id = $_REQUEST['post_id'];
switch ($action):
case 'dp_sep_delete':
// Enviamos a la papelera este post
wp_trash_post( $post_id );
break;
case 'dp_sep_update_title':
// Actualizamos el título del post
if( isset($_POST['post_title']) &&
!empty($_POST['post_title']) ):
$title = sanitize_text_field($_POST['post_title']);
wp_update_post(array(
'ID' => $post_id,
'post_title' => $title
));
endif;
break;
endswitch;
// Redireccionamos a la home
wp_safe_redirect( home_url() );
exit;
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment