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.

Lascia un commento

Il tuo indirizzo email non sarĂ  pubblicato. I campi obbligatori sono contrassegnati *