1

On every post there is a "read" (default) and "listen" button that users can click on without page refresh.

The listen tab can be accessed directly through

domain.com/category/post-title/?listen=listen

and

domain.com/category/post-title/listen/listen

I would like to edit the rewrite rule so that the same page can accessed though

domain.com/category/post-title/listen

How would I go about doing this?

My code:

function cp_narrations_query_vars( $qvars ) {
  $qvars[] = 'listen';
  return $qvars;
} add_filter( 'query_vars', 'cp_narrations_query_vars' , 10, 1 );

function cp_add_my_endpoint(){
    add_rewrite_endpoint( 'listen', EP_PERMALINK );
} add_action( 'init', 'cp_add_my_endpoint' );
  • 2
    you should already be able to do that with the code you have here, you just have to check if the listen query var exists rather than if it equals listen. – Milo Oct 2 '16 at 15:50
  • Didn't think of that. Should've thought of that. Thanks! – Swen Oct 2 '16 at 16:22
1

Answered thanks to Milo's comment.

I wrote a small function to check if the query variable exists. Note that get_query_var('listen') didn't work for me.

function is_listen() {    
    $vars = $GLOBALS['wp_query']->query_vars;

    if ( array_key_exists('listen', $vars) ) {
        return true;
    } else {
        return false;
    }       
}

Use it in a conditional like so:

if ( is_listen() ) {
    // Display listen tab
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.