add an external md file to a php page

… and, of course see it as html, with the same graphical appearance of any other web text.

A way can be use a very light javascript, md-block.js, di Lea Verou.

Then you can add a function to your php website, like the following:

<?php
/* to call a file Markdown from a given folder */

function scheda_md($file)
{
    global $yourwebsite;

    $file = basename($file);

    return '<md-block src="' .
           $yourwebsite .
           '/the-path/where-are-md-files/from-yourwebsite-root' .
           htmlspecialchars($file, ENT_QUOTES, 'UTF-8') .
           '"></md-block>';
}
?>

And in the page where you want to show that md file you can use this code:

<?= scheda_md('the-md-name.md') ?>



Php variables in WordPress

To set a variable, such as an url, you can use the following steps:

  • add to your wp-config a code with something like
require_once ABSPATH . 'wp-settings.php';
/** variabili */
define('GLOSSARIO_URL', 'yourwebsite/glossario.php');
  • add to functions.php (in your wp theme root) something like
define('GLOSSARIO_URL', 'yourwebsite/glossario.php');

function glossario_link($atts) {
    $atts = shortcode_atts([
        'id' => '',
        'testo' => ''
    ], $atts);

    $url = GLOSSARIO_URL . '#' . $atts['id'];

    return '<a href="' . esc_url($url) . '">' . esc_html($atts['testo']) . '</a>';
}

add_shortcode('glossario', 'glossario_link');
  • in wp editor you will be able to call that code inserting a text like this:
[glossario id="universalismo" testo="universalisticamente"]

where the content of testo="" is what will appears in your wp page (while in the editor you will see that code)

External markdown file in WordPress

If you want keep an external markdown file and include it in a WordPress page, you can follow these steps:

  • add a js file, such as md-block.js, in your js theme folder (typically /wp-content/themes/your-theme/js/ )
  • modify the functions.php file, in your root theme folder,. adding this code:
// per markdown BEGIN

function carica_md_block() {
    wp_enqueue_script(
        'md-block',
        get_stylesheet_directory_uri() . '/js/md-block.js',
        array(),
        null,
        true
    );
}
add_action('wp_enqueue_scripts', 'carica_md_block');

add_filter('script_loader_tag', function($tag, $handle, $src) {
    if ($handle === 'md-block') {
        return '<script type="module" src="' . esc_url($src) . '"></script>';
    }
    return $tag;
}, 10, 3);

function shortcode_scheda_md($atts) {
    $atts = shortcode_atts(array(
        'file' => ''
    ), $atts);

    $file = basename($atts['file']);

    if (empty($file) || pathinfo($file, PATHINFO_EXTENSION) !== 'md') {
        return '';
    }

    $url = content_url('/uploads/some-path/' . rawurlencode($file));

    return '<md-block src="' . esc_url($url) . '"></md-block>';
}
add_shortcode('scheda_md', 'shortcode_scheda_md');

// per markdown END
  • you can put your md files in the path above set: /uploads/some-path/ . Note that the folder some-path could be a symlinked one, from your local PC.
  • in the wordpress page when you want include a md file you can write,
    • using HTML (customized), [scheda_md file="the-name-of-the-file.md"],
    • or the code visualizaztion: something like[scheda_md]the-name-of-the-file.md[/scheda_md]
  • where that file, obviously, should be in /some-path/ folder.

Regex in Kate

It could be very difficult using regex in Kate, if you have php files that have still an html (and not php) as content structure.

In this case you can try to use, al filter, not *.php, but *.*.

Moreover it could be necessary to use this regex code for multiline tags :

<style type="text/css">((.|\n)*?)</style>

or

<script type="text/javascript">((.|\n)*?)</script>

and so on.

Automatically link youtube videos

You could try with a php function the following:

<?php
function getYouTubeVideosByTag($tag, $maxResults = 6) {
    $apiKey = '[your youtube API key]';
    $channelId = '[your-youtube-channel-ID';

    // Forza formato hashtag
    $query = urlencode('#' . $tag);

    $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&order=date&maxResults=$maxResults&q=$query&channelId=$channelId&key=$apiKey";

    $response = file_get_contents($url);

    if ($response === FALSE) {
        return [];
    }

    $data = json_decode($response, true);

    $videos = [];

    if (!empty($data['items'])) {
        foreach ($data['items'] as $item) {
            if (!isset($item['id']['videoId'])) continue;

            $videos[] = [
                'title' => $item['snippet']['title'],
                'videoId' => $item['id']['videoId'],
                'description' => $item['snippet']['description'],
                // 'thumbnail' => $item['snippet']['thumbnails']['medium']['url']
            ];
        }
    }

    return $videos;
}
?>

Obviously you have to link this function in every web page you want links your videos, and in these pages you can call that function by a code like this:

<?php
if (!empty($youtubetag)) {

    if (is_array($youtubetag)) {
        $query = implode(' OR ', array_map(fn($t) => '#' . $t, $youtubetag));
        $videos = getYouTubeVideos($query, 5);
    } else {
        $videos = getYouTubeVideosByTag($youtubetag, 3);
    }

    if (!empty($videos)) {
        ?>

        <section class="youtube-videos">
        <h2>🎙️ Our podcast (YouTube)</h2>

            <ul>
                <?php foreach ($videos as $video): ?>
                    <li class="podcast">🎙️
                        <a href="https://www.youtube.com/watch?v=<?= $video['videoId'] ?>"><strong><?= htmlspecialchars($video['title']) ?></strong></a>:
                       <?= htmlspecialchars(substr($video['description'], 0, 120), ENT_QUOTES | ENT_HTML5, 'UTF-8', false) ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </section>

        <?php
    }
}
?>

Finally, you should define, possibly in the head of each php page, where you want to link youtube videos, the variable $youtubetag:

$youtubetag="my tag";
or 
$youtubetag="['mytag1', 'mytag2']";

Set a flexible php variable

If you want php set a default variable value, but only if you yourself (in a particular case) set (before) another value of that variable, you can use a code like this:

$your_variable = $your_variable ?? $a_default_value;

That means: if you doesn’t define another value (with a code like $your_variable = "some_particular_value" ), the value of $your_variable will be $a_default_value.

Otherwise it will be "some_particular_value" .

Undesired empty rows in html source

Using php to generate automatically a webpage can produce undesired empty rows (typically at the begging of your source code, before <!DOCTYPE html>).
To avoid them you could have i.g. to remove empty rows between ?> and <?php, that is something like the follow code:

?>

<?php

The (new) working code should be

?>
<?php

On the contrary, empty rows inside <?php ... ?> blocks are not relevant.

In general, every empty (useless) row after a ?> could generate undesired empty rows in your html output source code.

Webtrees problems

Webtrees is a fork of PhpGedView, an excellent genealogy program. It ha a big problem: uploading and setting multimedial files.
It’s often a terrible waste of time: a very complicated way to upload files.

workaround

  • You can try to upload images (if you work in localhost and you know what you are doing) in this way:
  • 1. symlink an image to /media folder in /data webtrees folder.
  • 2. add that image file in phpmyadmin (your webtrees db) “media” and “media_file” tables (you have to set a number, such as X110).
    3. add to “individuals” the id of that file, with a code like “1 OBJE @X110@” at the bottom of the field i_gedcom.
  • 4. Now, in webtrees grafical view you has now to (pretend to) modify (nothing modifying, in fact) and save this modification.
  • 5. You could have also to save the modification date (saving the proposed one).

caveat

  • a. The file symlinked must have rights permissions (owner rw, group and others only r).
  • b. no avif: only jpg or webp are allowed.

You should now see the expected image within the page of that individual

Webtrees mysql error

It can happen that Webtrees gives an error such the following


SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value 

You can try to solve it, assigning an auto-increment default value to that field, in PhpMyAdmin

How to avoid double slash

If your link points to a folder it should ends with a slash (/), but if you use a php variable to define it and you sometimes need to add some page at the end of your link, you could have a problem: the double slash (//).
I.g. you could have this variable php

$mypath="mypath1/mypath2/";

The final slash is recommended to avoid a redirect (that you would have with $mypath="mypath1/mypath2).
And you can call that variable in all your webpages pointing at that folder, in this way:

<a href=”<?php echo $mypath ?>”>some name</a>

But if you have to point to a specific page in that folder, you shouldn’t use this code:

<a href="<?php echo "$mypath/a-specific-page.php" ?>">some other name</a>

otherwise you will get, in the final html, a double slash. No way, course to write $mypatha-specific-page.php , because in this case your would call a not existing variable ($mypatha-specific-page.php ).

A good solution could then be this

<a href="<?php echo $mypath . 'a-specific-page.php' ?>">some other name</a>