zeshan-a
4/4/2018 - 9:27 PM

WordPress Get Year and Month from URL

<?php // ignore this line

// $year and $monthnum are the variables to be used.

$year     = false;
$monthnum = false;
$matches  = array();
$matches2 = array();
$url      = $_SERVER['REQUEST_URI'];

preg_match("/CPT_SLUG_GOES_HERE\/([0-9]{4})\/([0-9]{1,2})\/?$/", $url, $matches);
preg_match("/CPT_SLUG_GOES_HERE\/([0-9]{4})\/([0-9]{1,2})\/page\/?([0-9]{1,})\/?$/", $url, $matches2);

if ( ! empty( $matches ) ) {
  $year     = $matches[2] ? $matches[1] : false;
  $monthnum = $matches[2] ? $matches[2] : false;
} elseif ( ! empty( $matches2 ) ) {
  $year     = $matches2[2] ? $matches2[1] : false;
  $monthnum = $matches2[2] ? $matches2[2] : false;
}