Code Bug Fix: “file_get_contents” in functions.php

Original Source Link

I want to display a number of a .txt file on my wordpress site via shortcode, I created a function in the functions.php of my theme

funtioncs.php:

<?php
[...]
function refresh_visitors()
{
   $visitor = file_get_contents(__DIR__ . '/../../uploads/visitors/currentvisits.txt' , true);
   //$visitor = 123;
   return $visitor;
}
add_shortcode( 'visitorcounter', 'refresh_visitors' );
[...]

In currentvisits.txt is a number e.g. 475.

For testing I created a Text block on my site with the created shortcode.

Visitor: [visitorcounter]

And… nothing happens.

When I manually set the variable $visitor to 123 it appears on my site…

I’ve just started with WordPress developing


UPDATE:

function refresh_visitors(){

global $wp_filesystem;

$file = '/path/to/file/currentvisits.txt';

if ($wp_filesystem->exists($file)) {
    $visitor = $wp_filesystem->get_contents($file);
    //$visitor = "FOUND";
} else {
    $visitor = "NOT FOUND";
}

return $visitor;
}
add_shortcode( 'visitorcount', 'refresh_visitors' );`

The $visitor variable is still empty …

Tagged : / / /

Leave a Reply

Your email address will not be published. Required fields are marked *