Text custom plugin path change

0
function deals_bh_visits() {

 $fichero = "visits_deals.txt";

 $fptr = fopen($fichero,"r");


 $num = fread($fptr,filesize($fichero));
 $num++;

 $fptr = fopen($fichero,"w+");
 fwrite($fptr,$num);
 fclose($fptr);
 return ("<span id='days_since'>$num</span>");
}
add_shortcode('deals_bh_visits', 'deals_bh_visits'); 

I have a problem, but before I will formulate what the following code does, this code creates a text file, with a number that increases each time you reload the web, that number is shown where the shortcode is placed.

I have only one problem, and that is that the file is not created in the same folder where the plugin is, it is created in the root of the web. How can I change the path of the text and believe in the same place?

    
asked by Juan David 20.02.2017 в 07:25
source

1 answer

1

The plugin is executed by means of an include of the path that the file displays, in this case /index.php . Since this is the entrypoint of all the views of a template, the shortcode is always executed as part of that script.

For what you want to do, you could take the function plugin_dir_path ( WP documentation ) that deals with as follows:

$dir = plugin_dir_path( __FILE__ ); 

$fichero = $dir. "visits_deals.txt";

$fptr = fopen($fichero,"r");

And with that the file will be created in the form:

/home/user/var/www/wordpress/wp-content/plugins/my-plugin/visit_deals.txt

Having said that ... are you sure you want to generate a new file for each visit? Will not it become a little unmanageable as soon as you have a couple of hundred hits?

    
answered by 20.02.2017 / 12:09
source