Last active
November 6, 2018 05:58
-
-
Save deryckoe/b51f53a4c3fd741d978631c7f0b8d383 to your computer and use it in GitHub Desktop.
WP Expertos/Author Profile Plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace WPE\Author; | |
class Profile { | |
/** | |
* Usuario que sera utilizando por los metodos de esta clase. | |
*/ | |
private $user; | |
/** | |
* Crear el metodo init permite ejecutar las acciones cuando sea necesario | |
* no es preciso hacerlo al instanciar la clase. | |
*/ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function init() { | |
/** | |
* Registramos el shortcode que utilizaremos en nuestra pagina plantilla | |
* para cargar el contenido del perfil de author. | |
*/ | |
add_shortcode( 'author_profile', array( $this, 'get_author_profile' ) ); | |
/** | |
* Registramos la carga del CSS. | |
*/ | |
add_action( 'wp_enqueue_scripts', array( $this, 'load_assets' ) ); | |
} | |
/** | |
* Cargamos el archivo CSS, finalmente. | |
*/ | |
public function load_assets() { | |
wp_enqueue_style( | |
'wpe-author-profile', | |
WPEAP_URL . 'assets/css/main.css', | |
array(), | |
filemtime( WPEAP_PATH . 'assets/css/main.css' ) | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Este metodo devuelve la informacion del author | |
* y es utlilizado por get_author_profile() | |
* | |
* @return string | |
*/ | |
private function author_box() { | |
$output = ''; | |
// Si no hay usuario, termina la funcion. | |
if ( empty( $this->user ) ) { | |
return $output; | |
} | |
// A partir de este punto, cualquier impresion se almacena en un buffer. | |
ob_start(); | |
// Hey WordPress, carga el usuario que viene en $this->user ;) | |
set_query_var( 'user', $this->user ); | |
// Cargamos la plantilla que da formato a la informacion del usuario. | |
load_template( WPEAP_PATH . 'views/author-box.php' ); | |
// Paso el buffer a una variable y lo limpio. | |
$output = ob_get_clean(); | |
return $output; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Este metodo devuelve las publicaciones del author | |
* y es utlilizado por get_author_profile() | |
* | |
* @return string | |
*/ | |
private function author_posts() { | |
$output = ''; | |
// Si el usuario no existe, termina el metodo. | |
if ( empty( $this->user ) ) { | |
return __( 'Este autor no existe.', 'wpe-author-profile' ); | |
} | |
// Si llega hasta aqui, existe, carguemos sus publiaciones. | |
$author_posts = new \WP_Query( array( | |
'nopaging' => 1, | |
'author' => $this->user->ID | |
) ); | |
// Existe pero no tiene publicaciones, termina el metodo. | |
if ( ! $author_posts->have_posts() ) { | |
return __( 'Este autor aún no tiene publicaciones.', 'wpe-author-profile' ); | |
} | |
// Si llega hasta aqui, tiene plublicaciones, imprimimos. | |
$output .= '<div class="author__posts">'; | |
$output .= '<h2 class="author__header">Publicaciones</h2>'; | |
while ( $author_posts->have_posts() ) { | |
$author_posts->the_post(); | |
// A partir de este punto, cualquier impresion se almacena en un buffer. | |
ob_start(); | |
// Cargamos la plantilla que da formato a cada publicacion existente. | |
load_template( WPEAP_PATH . '/views/author-post.php' ); | |
// Paso el buffer a una variable y lo limpio. | |
$output .= ob_get_clean(); | |
} | |
// Terminamos impresion. | |
$output .= '</div> <!-- .author__posts -->'; | |
// Restauramos $post y por tanto el Loop principal de WordPress | |
wp_reset_postdata(); | |
return $output; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Este metodo unifica la impresion en página del perfil del autor, | |
* con su bio y sus publicaciones. | |
* | |
* @return string | |
*/ | |
public function get_author_profile() { | |
global $wp_query; | |
$output = ''; | |
if ( ! empty ( $wp_query->query_vars['author_name'] ) ) { | |
$this->user = get_user_by( 'login', $wp_query->query_vars['author_name'] ); | |
$output .= $this->author_box(); | |
$output .= $this->author_posts(); | |
} else { | |
$output .= __( 'Selecciona un usuario para visualizar su perfil', 'wpe-author-profile' ); | |
} | |
return $output; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace WPE\Author; | |
class Profile { | |
/** | |
* Usuario que sera utilizando por los metodos de esta clase. | |
*/ | |
private $user; | |
/** | |
* Crear el metodo init permite ejecutar las acciones cuando sea necesario | |
* no es preciso hacerlo al instanciar la clase. | |
*/ | |
public function init() { | |
/** | |
* Registramos el shortcode que utilizaremos en nuestra pagina plantilla | |
* para cargar el contenido del perfil de author. | |
*/ | |
add_shortcode( 'author_profile', array( $this, 'get_author_profile' ) ); | |
/** | |
* Registramos la carga del CSS. | |
*/ | |
add_action( 'wp_enqueue_scripts', array( $this, 'load_assets' ) ); | |
} | |
/** | |
* Cargamos el archivo CSS, finalmente. | |
*/ | |
public function load_assets() { | |
wp_enqueue_style( | |
'wpe-author-profile', | |
WPEAP_URL . 'assets/css/main.css', | |
array(), | |
filemtime( WPEAP_PATH . 'assets/css/main.css' ) | |
); | |
} | |
/** | |
* Este metodo unifica la impresion en pagina del perfil del autor, | |
* con su bio y sus publicaciones. | |
* | |
* @return string | |
*/ | |
public function get_author_profile() { | |
global $wp_query; | |
$output = ''; | |
if ( ! empty ( $wp_query->query_vars['author_name'] ) ) { | |
$this->user = get_user_by( 'login', $wp_query->query_vars['author_name'] ); | |
$output .= $this->author_box(); | |
$output .= $this->author_posts(); | |
} else { | |
$output .= __( 'Selecciona un usuario para visualizar su perfil', 'wpe-author-profile' ); | |
} | |
return $output; | |
} | |
/** | |
* Este metodo devuelve la informacion del author | |
* y es utlilizado por get_author_profile() | |
* | |
* @return string | |
*/ | |
private function author_box() { | |
$output = ''; | |
// Si no hay usuario, termina la funcion. | |
if ( empty( $this->user ) ) { | |
return $output; | |
} | |
// A partir de este punto, cualquier impresion se almacena en un buffer. | |
ob_start(); | |
// Hey WordPress, carga el usuario que viene en $this->user ;) | |
set_query_var( 'user', $this->user ); | |
// Cargamos la plantilla que da formato a la informacion del usuario. | |
load_template( WPEAP_PATH . 'views/author-box.php' ); | |
// Paso el buffer a una variable y lo limpio. | |
$output = ob_get_clean(); | |
return $output; | |
} | |
/** | |
* Este metodo devuelve las publicaciones del author | |
* y es utlilizado por get_author_profile() | |
* | |
* @return string | |
*/ | |
private function author_posts() { | |
$output = ''; | |
// Si el usuario no existe, termina el metodo. | |
if ( empty( $this->user ) ) { | |
return __( 'Este autor no existe.', 'wpe-author-profile' ); | |
} | |
// Si llega hasta aqui, existe, carguemos sus publicaciones. | |
$author_posts = new \WP_Query( array( | |
'nopaging' => 1, | |
'author' => $this->user->ID | |
) ); | |
// Existe pero no tiene publicaciones, termina el metodo. | |
if ( ! $author_posts->have_posts() ) { | |
return __( 'Este autor aún no tiene publicaciones.', 'wpe-author-profile' ); | |
} | |
// Si llega hasta aqui, tiene plublicaciones, imprimimos. | |
$output .= '<div class="author__posts">'; | |
$output .= '<h2 class="author__header">Publicaciones</h2>'; | |
while ( $author_posts->have_posts() ) { | |
$author_posts->the_post(); | |
// A partir de este punto, cualquier impresion se almacena en un buffer. | |
ob_start(); | |
// Cargamos la plantilla que da formato a cada publicacion existente. | |
load_template( WPEAP_PATH . '/views/author-post.php' ); | |
// Paso el buffer a una variable y lo limpio. | |
$output .= ob_get_clean(); | |
} | |
// Terminamos impresion. | |
$output .= '</div> <!-- .author__posts -->'; | |
// Restauramos $post y por tanto el Loop principal de WordPress | |
wp_reset_postdata(); | |
return $output; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Utilizamos Namespaces, entras otras cosas para evitar | |
* duplicado de clases con otros plugin de WordPress. | |
*/ | |
namespace WPE\Author; | |
class Rewrite_Rules { | |
/** | |
* Esta variable sera el contenedor de la clase Settings, | |
* que se utilizando Dependency Injection, DI. | |
* | |
* @var Settings | |
*/ | |
private $settings; | |
/** | |
* Rewrite_Rules constructor. | |
* Se ejecuta en cuanto se instancia la clase. | |
* | |
* @param Settings $settings | |
*/ | |
public function __construct( Settings $settings ) { | |
// settings es igual a la instancia de la clase Settings. | |
$this->settings = $settings; | |
} | |
/** | |
* Crear el metodo init permite ejecutar las acciones cuando sea necesario | |
* no es preciso hacerlo al instanciar la clase. | |
*/ | |
public function init() { | |
/** | |
* Al inicializar WordPress, se ejecutan los métodos necesarios. | |
* | |
* url: https://developer.wordpress.org/reference/functions/add_action/ | |
*/ | |
add_action( 'init', array( $this, 'custom_author_url' ) ); | |
add_action( 'init', array( $this, 'custom_rewrite_rule' ), 10, 0 ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Utilizamos Namespaces, entras otras cosas para evitar | |
* duplicado de clases con otros plugin de WordPress. | |
*/ | |
namespace WPE\Author; | |
class Rewrite_Rules { | |
/** | |
* Esta variable sera el contenedor de la clase Settings, | |
* que se utilizando Dependency Injection, DI. | |
* | |
* @var Settings | |
*/ | |
private $settings; | |
/** | |
* Rewrite_Rules constructor. | |
* Se ejecuta en cuanto se instancia la clase. | |
* | |
* @param Settings $settings | |
*/ | |
public function __construct( Settings $settings ) { | |
// settings es igual a la instancia de la clase Settings. | |
$this->settings = $settings; | |
} | |
/** | |
* Crear el metodo init permite ejecutar las acciones cuando sea necesario | |
* no es preciso hacerlo al instanciar la clase. | |
*/ | |
public function init() { | |
/** | |
* Al inicializar WordPress, se ejecutan los metodos necesarios. | |
* | |
* url: https://developer.wordpress.org/reference/functions/add_action/ | |
*/ | |
add_action( 'init', array( $this, 'custom_author_url' ) ); | |
add_action( 'init', array( $this, 'custom_rewrite_rule' ), 10, 0 ); | |
} | |
/** | |
* Crea la regla de url que registara y leera el parametro author_name cuando el formato | |
* sea "Pretty Permalinks". | |
* | |
* https://codex.wordpress.org/Using_Permalinks | |
*/ | |
function custom_rewrite_rule() { | |
// Utilizando Dependency Injection obtenemos la página de author creada las preferencias. | |
$author_profile_page_id = $this->settings->get_author_profile_page_id(); | |
// Si no hay id de pagina es que no hay ninguna asignada y la funcion termina aqui. | |
if ( false === $author_profile_page_id ) { | |
return; | |
} | |
//Si hay, pedimos la pagina completa. | |
$page = get_post( $author_profile_page_id ); | |
if ( null !== $page && '' != $page->post_name ) { | |
// Si existe la pagina y tiene slug, podemos crear la regla de url. | |
add_rewrite_rule( '^' . $page->post_name . '/([^/]*)/?', 'index.php?page_id=4&author_name=$matches[1]', 'top' ); | |
} | |
} | |
/** | |
* Sobreescribe la url por defecto de cada autor. | |
* De esta forma podemos utilizar el nuevo perfil de autor como estandar. | |
*/ | |
public function custom_author_url() { | |
global $wp_rewrite; | |
// Utilizando Dependency Injection obtenemos la pagina de author creada las preferencias. | |
$page_id = $this->settings->get_author_profile_page_id(); | |
// Dejamos solo la parte final de la url de author, que es la que necesitamos, sin / final. | |
$author_slug = untrailingslashit( str_replace( get_home_url(), '', get_permalink( $page_id ) ) ); | |
// Aqui se hace la modificacion de la url por defecto de cada autor. | |
$wp_rewrite->author_base = $author_slug; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace WPE\Author; | |
class Settings { | |
/** | |
* Crear el metodo init permite ejecutar las acciones cuando sea necesario | |
* no es preciso hacerlo al instanciar la clase. | |
*/ | |
public function init() { | |
add_action( 'admin_init', array( $this, 'wpe_register_setting' ) ); | |
add_action( 'init', array( $this, 'eval_flush_rewrite_rules' ) ); | |
/** | |
* Esta accion se ejecuta cuando actualizamos | |
* el ID de pagina de author, en las preferencias. | |
*/ | |
add_action( 'update_option_author_profile_page_id', array( | |
$this, | |
'insert_shortcode' | |
), 10, 2 ); | |
} | |
/** | |
* Este metodo se encarga de crear el selector de pagina de | |
* perfil de autor en las preferencias. | |
*/ | |
public function wpe_register_setting() { | |
// Creamos las seccion, al final de Generales | |
add_settings_section( | |
'general_author_section', | |
'Perfil de autor', | |
array( $this, 'general_author_section_description' ), // al registrar, llama este metodo. | |
'general' | |
); | |
// Registramos el valor, para que se actualice en base de datos. | |
register_setting( 'general', 'author_profile_page_id' ); | |
// Registramos el campo, asociado a la seccion antes registrada. | |
add_settings_field( | |
'author_profile_page_id', | |
'This is the setting title', | |
array( $this, 'author_profile_page_id_select' ), | |
'general', | |
'general_author_section', | |
array( | |
'label_for' => 'author_profile_page_id' | |
) | |
); | |
} | |
/** | |
* Devuelve la descripcion de la seccion registrada. | |
* En este caso, nada. | |
*/ | |
public function general_author_section_description() { | |
echo ''; | |
} | |
/** | |
* Imprime un select con el listado de paginas disponibles. | |
* | |
* @param $args | |
*/ | |
public function author_profile_page_id_select( $args ) { | |
echo '<select name="' . $args['label_for'] . '" id="' . $args['label_for'] . '">'; | |
echo '<option value="0">-- Selecciona --</option>'; | |
$author_profile_page_id = get_option( 'author_profile_page_id' ); | |
$pages = get_pages( array( 'status' => array( 'pending', 'draft', 'future' ) ) ); | |
if ( ! is_wp_error( $pages ) ) { | |
foreach ( $pages as $page ) { | |
printf( | |
'<option value="%s" %s >%s</option>', | |
$page->ID, | |
selected( $author_profile_page_id, $page->ID, false ), | |
$page->post_title | |
); | |
} | |
} | |
echo '</select>'; | |
} | |
/** | |
* Este metodo inserta automaticamente en la pagina seleccionada | |
* el shortcode que imprime el perfil de author siempre que esta | |
* no tenga contenido, de lo contrario, no la toca, por seguridad. | |
* | |
* @param $old_value | |
* @param $value | |
*/ | |
public function insert_shortcode( $old_value, $value ) { | |
if ( $value === $old_value ) { | |
return; | |
} | |
$page = get_post( $value ); | |
if ( '' == trim( $page->post_content ) ) { | |
wp_update_post( array( | |
'ID' => $value, | |
'post_content' => '[author_profile]' | |
) ); | |
} | |
// La proxima vez que cargue, reestablece las reglas de URL. | |
add_option( 'next_time_force_reflush', '1' ); | |
} | |
/** | |
* Reestablece las reglas de URL, hazlo. | |
*/ | |
public function eval_flush_rewrite_rules() { | |
if ( '1' === get_option( 'next_time_force_reflush' ) ) { | |
// Si al cargar existe la "orden" de reestablecer las reglas de URL, hazlo. | |
flush_rewrite_rules(); | |
// Elimina esa "orden" para que no ocurra cada vez que cargue. | |
delete_option( 'next_time_force_reflush' ); | |
} | |
} | |
/** | |
* Evalua que esta registrado el ID de pagina de author y lo devuelve. | |
* En caso de que no, revuelve false. | |
* | |
* Este metodo es utilizando por otras clases del plugin | |
* mediante Dependency Injection (DI). | |
* | |
* @return bool|mixed | |
*/ | |
public function get_author_profile_page_id() { | |
$id = get_option( 'author_profile_page_id' ); | |
// Utilizamos un ternario para devolver ID o false, si no existe ID. | |
return ( 0 <= $id ) ? $id : false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment