Receive a parameter through a friendly URL on a Wordpress page

Asked

Viewed 693 times

1

I have a Wordpress page called Recordings which is accessed through http://localhost/Recordings and I need to pass an ID parameter at the end of the URL that can be used later to create dynamic content on the Wordpress page. Example: http://localhost/Recordings/123, and via PHP get the ID 123.

NOTE: Need to be via friendly URL and not via querystring (Recordings/? id=123).

How to do this? What is the best practice and standard Wordpress for this purpose?

  • I just realized that I had already answered a similar question... as the code is slightly different I will leave the answer below instead of deleting

1 answer

1


Must use a endpoint through function add_rewrite_endpoint():

# conferir outras possibilidades além do EP_ALL na documentação
add_rewrite_endpoint( 'recordings', EP_ALL );

The endpoint should be added to query_vars:

add_filter( 'query_vars', function( $vars ){
    $vars[] = 'recordings';
    return $vars;
});

From there, you can check any URL of the site:

# Exemplo de URL: http://example.com/post-name/recordings/Nome do Disco/
$recordings = get_query_var( 'recordings','' );
# $recordings vai ser igual a "Nome do Disco"

The add_rewrite_endpoint only needs to be called once and one must make a refresh permalinks. Translated into a plugin looks like this:

<?php
/**
 * Plugin Name: Adicionar Custom Endpoint
 * Plugin URI:  /a/204365/201
 * Author: brasofilo
 */

register_activation_hook(   __FILE__, array( 'SOPT_Endpoint', 'activation' ) );

add_action( 'plugins_loaded',  array ( SOPT_Endpoint::get_instance(), 'plugin_setup' ) );

class SOPT_Endpoint {
    /**
     * Plugin instance.
     */
    protected static $instance = NULL;

    /**
     * Constructor. Intentionally left empty and public.
     */
    public function __construct() {}    

    /**
     * Access this plugin’s working instance
     */
    public static function get_instance(){
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    /**
     * Refresh permalinks on plugin activation
     * Source: http://wordpress.stackexchange.com/a/108517/12615 
     */
    public static function activation(){
        if ( ! current_user_can( 'activate_plugins' ) )
            return;

        $plugin = isset( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';
        check_admin_referer( "activate-plugin_{$plugin}" );

        #source: http://wordpress.stackexchange.com/a/118694/12615
        add_rewrite_endpoint( 'recordings', EP_ALL ); 
        flush_rewrite_rules();
    }

    /**
     * Inicio do plugin
     */
    public function plugin_setup(){
        add_filter( 'query_vars', array( $this, 'query_vars' ) );
        # Só para demonstrar o plugin funcionando
        add_action( 'wp_footer', array( $this, 'wp_footer' ) );
    }

    public function query_vars( $vars ){
        $vars[] = 'recordings';
        return $vars;       
    }

    # Função para demonstrar como capturar o endpoint
    # - visitar qualquer URL do site e acrescentar /recordings/VARIAVEL
    # - - conferir o rodapé da página para ver o resultado
    public function wp_footer(){
        $recordings = get_query_var( 'recordings','' );
        if( '' === $recordings ) {
            echo '<h1 style="font-size:4em">Endpoint sem variável.</h1>';
        } 
        else {
            printf( '<h1 style="font-size:4em">Variável do endpoint: %s</h1>', urldecode( $recordings ) );
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.