Support » Fixing WordPress » Simple javascript

  • I’d like to include one simple javascript function in about a third of the posts on my site. I’ve studied how to do this for several hours, tested several plugins, edited various files in my theme, etc., but I just can’t seem to make it work, and would appreciate advice.

    The function just tests for the date and either inserts a link in a reference to a post, or doesn’t. (So that there’s only a link after the post is live, and the link is functional.)

    Here’s my function:

    $(function() {
    var ds = $(“.dateswitch”),
    now = new Date();
    if (Date.parse(ds.data(“switchdate”)) < now) {
    ds.find(“.beforeswitch”).hide();
    ds.find(“.afterswitch”).show();
    }
    });

    And here’s html that uses it:

    <p class=”dateswitch” data-switchdate=”2017-07-04″>
    The post
    <span class=”beforeswitch”>“Test Post” will be</span>
    <span class=”afterswitch” style=”display:none;”>“Test Post” was</span>
    published on Friday, 4 August 2017.
    </p>

    I’m mildly competent with basic WP issues, but completely new to javascript. (I got this script from someone else.) I’ve tried including my function in a javascript file in my theme, and calling that; including it in the footer; including it just in the post; including it in several plugins; etc., but it just doesn’t work. (It works just fine as a js fiddle, so I’m confident of the function itself.)

    My question:
    How exactly should I include this function in my posts?

    • If as a js file, where should I put it, and how should I call it? For example, should I call it with a fixed address (a normal web url) or use get_theme_root_uri?
    • If in the footer, do I just put this function inside a script tage? If so, what exactly should it look like?
    • Does the function need a name of some kind? So far, I’ve just put the exact function above in the js file, and used the exact html above. Do I need to include some reference to the specific function? How?

    If there’s an easier way, I’m happy to use it. I looked at advice on enqueueing, but I think it’s beyond me. I’ve tried the plugins Scripts n Styles and Simple Custom CSS and JS, but the function still didn’t work. My guess is that I’m making a reference mistake somewhere, but I’m not sure where. My theme is called Nirvana-child-testing, if that helps in specifying references and locations.

Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator cubecolour

    (@numeeja)

    $(function() indicates that the script requires jquery, so that needs to be included in addition to the script.

    You can build and activate a WordPress plugin to use this script.

    To build the plugin, create a folder called ‘dateswitch’ in your wp-content/plugins directory and inside that make a file called dateswitch.php with the following content:

    
    <?php
    /*
    Plugin Name: Dateswitch
    Description: Add the dateswitch script to the footer of all pages
    Version: 1.0.0
    Author: cubecolour
    */
    
    /**
     * function to output the dateswitch script
     *
     */
    function dateswitch_script(){
    
    	$ds_script ='<script>
    	jQuery(function() {
    	var ds = jQuery(".dateswitch"),
    		now = new Date();
    		if (Date.parse(ds.data("switchdate")) < now) {
    			ds.find(".beforeswitch").hide();
    			ds.find(".afterswitch").show();
    		}
    	});
    	</script>';
    
    	echo $ds_script;
    }
    
    /**
     * dateswitch shortcode
     * usage [dateswitch date="2017-07-29"]
     *
     */
    function shortcode_dateswitch( $atts, $content = null ) {
    
        $args = shortcode_atts( array(
    		'date'	=> '',			//* yy:-mm-dd
    		'title'	=> 'The Post',	//* post title
    		'url'	=> '',			//* post url
    	), $atts, 'dateswitch' );
    
    	/**
    	 * Sanitize the Date value
    	 *
    	 */
    	$args['date'] = preg_replace("([^0-9-])", "", $args['date'] );
    
    	/**
    	 * Sanitize the Title value
    	 *
    	 */
    	$args['title'] = sanitize_text_field( $args['title'] );
    
    	/**
    	 * Sanitize the URL value
    	 *
    	 */
    	$args['url'] = esc_url( $args['url'] );
    
    	/**
    	 * Convert Date format to text
    	 *
    	 */
    	$longdate = date( "l, j F Y", strtotime( $args['date'] ));
    
    	/**
    	 * Output (nothing if the date parameter is missing)
    	 *
    	 */
    	if ($args['date'] == "") {
    
    		return;
    
    	} else {
    		/**
    		 * Enqueue jQuery, include the dateswitch script in the footer, & output the text.
    		 *
    		 */
    
    		wp_enqueue_script( 'jquery' );
    		add_action('wp_footer', 'dateswitch_script', 20);
    
    		$output = '<p class="dateswitch" data-switchdate="' . $args['date'] . '">
    The post <span class="beforeswitch">"' . $args['title'] . '" will be</span><span class="afterswitch" style="display:none;">"<a href="' . $args['url'] . '">' . $args['title'] . '</a>' . '" was</span> published on ' . $longdate . '</p>';
    
    		return $output;
    	}
    }
    
    add_shortcode( 'dateswitch', 'shortcode_dateswitch' );
    

    On the pages where you want this to appear you would add a shortcode:

    [dateswitch title="Page title" url="http://url.of.page" date="2017-07-29"]

    Where the values of the Page title, url, and date parameter are equivalent to the corresponding information you were using in your original html.

    The code is commented, so I won’t go into long explanations, but you will see the code to register a shortcode and accept parameters, sanitize the parameter values, include the script in the footer, enqueue jquery (which is required for the script), and you can compare how the script has been changed from the original to ensure compatibility with the way WordPress uses jquery.

    Thread Starter Evil Overlord

    (@evil-overlord)

    @cubecolour

    Thanks very much! I hadn’t hoped for such a thorough reply, but I very much appreciate it. I’ve made a simple plugin before, so should be able to manage that.

    I’ll give this a try now, and let you know how it works out.

    Thread Starter Evil Overlord

    (@evil-overlord)

    Works!

    Here are a few things I learned, and one question:

    • I added ?> to close the php for the plugin.
    • I didn’t think it through, and put two shortcodes with different dates (one before, one after) in the same post. They both came out with the same format. When I finally tested with just one, it worked fine.
    • Question: I need to add one more variable, which seems straightforward, but I also need the result to include an apostrophe and quotation marks. What’s the right way to escape these?

    For the new variable (author), I just made the variable list:

    $args = shortcode_atts( array(
    ‘date’ => ”, //* yy:-mm-dd
    ‘title’ => ‘Story’, //* story title
    ‘url’ => ”, //* post url
    ‘author’ => ”, //* author’s name
    ), $atts, ‘dateswitch’ );

    For the result, I need it to look like the below, where apostrophe stands for ‘, and openquote/closequote stand for quotation marks.

    $args[‘author’]’ . ‘apostrophes story”‘ . <span class=”beforeswitch”>”‘ . $args[‘title’] . ‘” will be</span><span class=”afterswitch” style=”display:none;”>” openquote’ . $args[‘title’] . ‘‘ . ‘closequote” was</span> published on ‘ . $longdate . ‘</p>’;

    Or:
    Jim Smith’s story “Great Story” will be published on 1 August 2017.

    • This reply was modified 4 years, 2 months ago by Evil Overlord.
    Moderator cubecolour

    (@numeeja)

    The closing ?> in a php file is optional and not required. I always omit it as it can cause unwanted whitespace at the end of files when using include() or require()

    The jquery script used selectively hides any elements with the class ‘beforeswitch’ and unhides any elements with the class ‘afterswitch’ if the condition is met. When two sets of the code is on the page, the script does not differentiate between them.

    To fix this, each instance could be given a unique class, id, or other identifier which can be targeted by the script, however this issue would probably be better addressed by building the output from each shortcodes in the php of the shortcode function so that only the required text is actually output rather than outputting two alternatives where one is shown and one is hidden by the jquery script. Then the script could be removed as it would not be needed.

    To be able to use punctuation in the title, a solution might be for the shortcode function to be changed so that enclosing shortcodes are used where the enclosed content is used as the title instead of there being a title parameter in a self-closing shortcode.

    Thread Starter Evil Overlord

    (@evil-overlord)

    @cubecolour

    Thanks. The initial plugin didn’t install, and I just assumed it was due to the missing ?>, but perhaps I’d made some other mistake.

    I only need this once per page, so it should work fine as is; I just confused myself by trying to test two variant shortcodes at once

    Is there a way for the shortcode to produce two outputs, or would I need two shortcodes? In my case, the story title (with/without link) needs to be within quotes, and the “was/will be” grammar outside the quotes. I like the idea of doing all this within the shortcode php, since I’m slightly more familiar with that than with javascript.

    Thread Starter Evil Overlord

    (@evil-overlord)

    Figured all this out. Your shortcodes approach was the key, and I realized that I already have and (slightly) know how to use the Custom Content Shortocde plugin, which will handle all this for me.

    Still going to learn from your code though, so I can figure out how to create my own shortcodes as necessary.

    Thanks again!

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Simple javascript’ is closed to new replies.