WordPress.org

Ready to get started?Download WordPress

Forums

Redirect user when clicking a blog post (5 posts)

  1. royofnorway
    Member
    Posted 1 year ago #

    Hi,

    I am currently configuring wordpress with a custom theme and I have the following need for customization:

    When I create a blog post it is made with a canonical url like this: domain.com/6-way-to-celebrate-love.

    When visitors click the blog post from the frontpage he is redirected to the blog page (singlepost.php) if I am correct?

    So far, so good...but:

    Instead of being redirected to singlepost.php I want him redirected to a new URL: "domain.com/ref" where a couple parameters are also sent along as GET. In the "ref" folder I have an index.php that will take these parameters:

    extURL (custom field in blog post)
    title (from the blog post)

    The page title of index.php is set to the title parameter and after 5 seconds the user is redirected to extURL.

    The reason for the 5 seconds delay is because I want to display a text before redirecting to the external site.

    Thanks so much for any help on this!

  2. You will want to use the add_query_arg() function for adding the parameters.

    In the template file that has the post links setup, you will want to replace the_permalink() with something like this:

    echo add_query_arg( array( 'one' => 'value', 'two' => value2' ), home_url( 'index.php' ) );

  3. royofnorway
    Member
    Posted 1 year ago #

    Thanks for the fast response, but I am not following. I am pretty new to WP so I'd appreciate if you could elaborate a bit more.

  4. Spencer Cameron
    Member
    Posted 1 year ago #

    I agree with Pippin. That's a great way to do it. Just make sure you escape the url before you echo it for safety's sake.

    echo esc_url( add_query_arg( array( 'one' => 'value', 'two' => value2' ), home_url( 'index.php' ) ) );

    Additionally, you should probably urlencode your query arguments before passing them to add_query_arg.

    add_query_arg( array( 'one' => urlencode( $value1 ), 'two' => urlencode( $value2 ) ), home_url( 'index.php' ) );

  5. Spencer Cameron
    Member
    Posted 1 year ago #

    To be clearer, somewhere in your homepage you must have a call to the_permalink() or echo get_permalink(), right? This should be inside of an anchor tag ( <a> ). Replace that call with the url you would like the user to be directed to. :) Does that make more sense? Maybe something like this:

    Before:
    <a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a>

    Direct user to custom url:
    <a href="<?php echo $custom_url; ?>" ><?php the_title(); ?></a>

    Is that any clearer? If not, post your code that outputs the post titles/links in your homepage. :)

Topic Closed

This topic has been closed to new replies.

About this Topic