Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cdsaenz/e5d4bbe88f2d7fee2301544f94f5c1ac to your computer and use it in GitHub Desktop.
Save cdsaenz/e5d4bbe88f2d7fee2301544f94f5c1ac to your computer and use it in GitHub Desktop.
PHP: Wordpress URL Segments
Add to header or function file:
<?php
// URL Segments and Master ID
//
// Segment Variables: $GLOBALS['segment']['1'], $GLOBALS['segment']['2'], etc.
// Master ID Variable: $GLOBALS['master_id']
global $segment;
global $master_id;
$segment = explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
$last_segment_array = array_slice($segment, -2, 1, true);
$last_segment = array_shift($last_segment_array);
$master_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '$last_segment'");
?>
Example Usage:
<?php if ($GLOBALS['segment']['1'] == 'test-1') : ?>
<!-- If True -->
<?php endif; ?>
<?php if ($GLOBALS['segment']['1'] == 'test-1' && $GLOBALS['segment']['2'] == 'test-2') : ?>
<!-- If True -->
<?php endif; ?>
<?php if ($GLOBALS['master_id'] == '10') : ?>
<!-- If True -->
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment