skip to Main Content

I’m using below function to redirect a specific url to a specific php script file:

add_action('wp', function() {
if ( trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/') === 'pagename' ) {
include(locate_template('give_some.php'));
exit();
}});

it works only for the specified url and i want to make it work for multiple urls. Suppose a file urls.txt contain numbers of url and for which above code have to be triggered. Any idea how to do this?

2

Answers


  1. I’m a long-time WordPress developer, and one of the best responses to a WordPress problem is “that’s not a WordPress problem, just simple PHP (or JavaScript)” one. That’s a really good thing because it makes it really easy to talk about.

    Your problem, as I understand it, is that you want to compare the current URL to a “file” of possible paths. You’ve got the WordPress equivalent of “current URL”, so I’ll take that for granted, and I’ll also assume you can take a file and convert it into an array. But once you do that, you are parsing a URL (which you already did) and seeing if it is in the array:

    $url = 'https://www.example.com/pagename?a=b&c=d';
    
    $paths = [
        'gerp',
        'pagename',
        'cheese',
    ];
    
    
    $path = trim(parse_url($url, PHP_URL_PATH), '/');
    if ( in_array($path, $paths )) {
        echo 'yes';
    } else {
        echo 'no';
    }
    

    Demo: https://3v4l.org/NOmpk

    Login or Signup to reply.
  2. You can use different hook request. Which allow you to manipulate request.

    add_filter( 'request', function( $request ){});
    

    My simple example ( not tested ).

    add_filter( 'request', function( $request ){
            $data = file_get_contents("database.txt"); //read the file
            $rows = explode("n", $data); //create array separate by new line
            $rows = array_map("trim", $rows); // for removing any unwanted space
            $rowCount = count($rows); // Count your database rows
    
            for ($i=0; $i < $rows ; $i++) {
                if( isset( $request['pagename'] ) && $rows[$i] == $request['pagename'] ){
                  include(locate_template('give_some.php'));
                }
            }
    
        return $request;
    });
    

    My advice, don’t use .txt files, save your data into database, and then use it, or create wp_option field, and manage from Settings page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search