Question

I have some script I want to add to my wordpress page (which contains Latex math, for which I use MathJax), so what I used to do is edit header.php in my themes, which is OK, except that every time I do an update, I have to edit that again and again... which is annoying and some times I forget to do that.

Is there anyway I could set that script permanently even after an update?

Was it helpful?

Solution 2

The solution is to create your own plug-in, which turns our to be much simpler than anyone thinks.

1- Pick a name for your plugin, I'll call it MyPlugin

2- Open a folder in your /wp-content/plugins/MyPlugin

3- Open a file inside the latter folder and call it MyPlugin.php

4- Input the following in that file:

<?php
/*
Plugin Name: MyPlugin
*/
function add_my_header() {
    echo '<script type="text/x-mathjax-config">';
    echo 'MathJax.Hub.Config({';
    echo 'tex2jax: {inlineMath: [[\'$\',\'$\']]}';
    echo '});';
    echo '</script>';
    echo '<script type="text/javascript"';
    echo '  src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG">';
    echo '</script>';
}
add_action( 'get_header', 'add_my_header' );
?>

You may change the script as you want.

5- Enable the plugin.

6- You're done! Give me a thumbs-up, and have fun :)

OTHER TIPS

Yes, you should be using the wp_enqueue_script() function. This will allow you to add a script to the wp_head() function's output. You can place this in your functions file and it will keep the script even if you update the header.php file or the plugin. You can do this with stylesheets as well. You should also apply an action hook so that the script loads at the proper time. Here is the code:

function add_my_scripts() {
    wp_enqueue_style ('style-name', get_stylesheet_uri() );
    wp_enqueue_script('script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
}

add_action( 'wp_enqueue_scripts', 'add_my_scripts' );

Note: the first argument for the functions is the unique identifier for the asset. As such, you should have a unique name for each script and style you add. You may need to use these later for dependancies or to unqueue something. The wordpress codex goes more into this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top