Skip to content

Instantly share code, notes, and snippets.

@rogerhub
Created January 7, 2014 21:03
Show Gist options
  • Save rogerhub/8306875 to your computer and use it in GitHub Desktop.
Save rogerhub/8306875 to your computer and use it in GitHub Desktop.
Enables the %monthcode% and %monthname% tag for permalinks in WordPress.
<?php
/**
* Plugin Name: Month Name
* Description: Enables the <code>%monthcode%</code> and <code>%monthname%</code> tag for Permalinks.
* Author: Roger Chen
* License: GPLv2
*/
/**
* Enables use of monthname (january, june) and monthcode (jan, jun).
* Supports permalinks in the form of /2016-nov/61742/..slug.. or /2016-november/61742/..slug..
*/
class MonthName {
/**
* Month Names
*/
public static $monthnames = array(
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december',
);
/**
* Month Codes
*/
public static $monthcodes = array(
'jan',
'feb',
'mar',
'apr',
'may',
'jun',
'jul',
'aug',
'sep',
'oct',
'nov',
'dec',
);
/**
* Registers all required hooks
*/
public static function init() {
add_rewrite_tag( '%monthname%', '(' . implode('|', self::$monthnames) . ')' );
add_rewrite_tag( '%monthcode%', '(' . implode('|', self::$monthcodes) . ')' );
add_rewrite_rule(
'^([0-9]{4})-(' . implode( '|', self::$monthnames ) . ')/([0-9]+)/?',
'index.php?p=$matches[3]',
'top'
);
add_rewrite_rule(
'^([0-9]{4})-(' . implode( '|', self::$monthcodes ) . ')/([0-9]+)/?',
'index.php?p=$matches[3]',
'top'
);
}
/**
* Filters the month name and month code tags
*/
public static function filter_post_link( $permalink, $post ) {
if ( false === strpos( $permalink, '%monthname%' ) && false === strpos( $permalink, '%monthcode%' ) ) {
return $permalink;
}
try {
$monthindex = intval(get_post_time( 'n', "GMT" == false, $post->ID ));
$monthname = self::$monthnames[$monthindex - 1];
$monthcode = self::$monthcodes[$monthindex - 1];
$permalink = str_replace( '%monthname%', $monthname, $permalink );
$permalink = str_replace( '%monthcode%', $monthcode, $permalink );
return $permalink;
} catch (Exception $e) {
return $permalink;
}
}
}
add_action( 'init', array( 'MonthName', 'init' ) );
add_filter( 'post_link', array( 'MonthName', 'filter_post_link' ), 10, 2 );
@gnath
Copy link

gnath commented Nov 20, 2014

It will work with post_id but not post_name. Can you please say how to make it work with post_name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment