Retrieve WordPress root directory path?

后端 未结 13 1368
闹比i
闹比i 2020-11-28 07:48

How can I retrieve the path to the root directory in WordPress CMS?

相关标签:
13条回答
  • 2020-11-28 08:15

    For retrieving the path you can use a function <?php $path = get_home_path(); ?>. I do not want to just repeat what had been already said here, but I want to add one more thing:

    If you are using windows server, which is rare case for WordPress installation, but still happens sometimes, you might face a problem with the path output. It might miss a "\" somewhere and you will get an error if you will be using such a path. So when outputting make sure to sanitize the path:

    <?php 
    
    $path = get_home_path(); 
    $path = wp_normalize_path ($path);
    
    // now $path is ready to be used :)
    
    ?>
    
    0 讨论(0)
  • 2020-11-28 08:24

    If you have WordPress bootstrap loaded you can use get_home_path() function to get path to the WordPress root directory.

    0 讨论(0)
  • 2020-11-28 08:26
       Please try this for get the url of root file.
    

    First Way:

     $path = get_home_path();
       print "Path: ".$path; 
    // Return "Path: /var/www/htdocs/" or
    
    // "Path: /var/www/htdocs/wordpress/" if it is subfolder
    

    Second Way:

    And you can also use 
    
        "ABSPATH"
    
    this constant is define in wordpress config file.
    
    0 讨论(0)
  • 2020-11-28 08:26

    I like @Omry Yadan's solution but I think it can be improved upon to use a loop in case you want to continue traversing up the directory tree until you find where wp-config.php actually lives. Of course, if you don't find it and end up in the server's root then all is lost and we return a sane value (false).

    function wp_get_web_root() {
    
      $base = dirname(__FILE__);
      $path = false;
    
      while(!$path && '/' != $base) {
        if(@file_exists(dirname($base)).'/wp-config.php') {
          $path = dirname($base);
        } else {
          $base = dirname($base);
        }
      }
    
      return $path;
    }
    
    0 讨论(0)
  • 2020-11-28 08:28

    I think this would do the trick:

    function get_wp_installation()
    {
        $full_path = getcwd();
        $ar = explode("wp-", $full_path);
        return $ar[0];
    }
    
    0 讨论(0)
  • 2020-11-28 08:32

    theme root directory path code

     <?php $root_path = get_home_path(); ?> 
    print "Path: ".$root_path;
    

    Return "Path: /var/www/htdocs/" or "Path: /var/www/htdocs/wordpress/" if it is subfolder

    Theme Root Path

     $theme_root = get_theme_root();
     echo $theme_root
    

    Results:- /home/user/public_html/wp-content/themes

    0 讨论(0)
提交回复
热议问题