Momentjs in wp doesn't work

Hello everyone,

I am trying to get momentjs working on wp but it keeps telling me moment.tz is undefined and no function.
Could somebody check what is wrong with the code ?

jQuery(document).ready(function() {
	jQuery.when(
		jQuery.getScript("//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"),
  		jQuery.getScript("//cdnjs.cloudflare.com/ajax/libs/jquery.countdown/2.1.0/jquery.countdown.min.js"),
    	jQuery.getScript("//cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.4/moment-timezone-with-data.min.js"),
	    jQuery.Deferred(function( deferred ){
        	jQuery( deferred.resolve );
    	})
	).done(function(){

    	var i = moment.tz("2017-07-07 23:59", "Europe/Amsterdam");
    	jQuery("#dutchTimer").countdown(i.toDate(), function(t) {
    		jQuery(this).html(t.strftime("%D dagen %H:%M:%S"));
    	});
	});
});

Best regards.

The error you’re seeing is because the scripts are being loaded in the wrong order. You need to load Moment before loading Moment Timezone and due to the nature of $.when(), this isn’t happening. Is there any reason you’re using $.when(), BTW?

The simplest way to accomplish what you want is:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.4/moment-timezone-with-data.min.js"></script>
<script>
  console.log(moment.tz('2017-07-07 23:59', 'Europe/Amsterdam'))
</script>

Gives you:


Moment {_isAMomentObject: true, _i: "2017-07-07 23:59", _f: "YYYY-MM-DD HH:mm", _isUTC: true, _pf: Object…}
1 Like

well I did not want to hack in wp so tried it like that.
Afterwards changed it to that and it worked.

Well the “wordpress way” would be to register and enqueue them in your theme’s functions.php (or plugin entry PHP script, if that’s where they’re needed); this way you can specify which scripts depend on each other, and let WP ensure that all scripts are available when they’re needed.

Usually you can perfectly get away with just hard-coding the links at the bottom of the body, though. :-)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.