Skip to content

Instantly share code, notes, and snippets.

@jtsternberg
Last active September 25, 2017 05:02
Show Gist options
  • Save jtsternberg/4a27bb8dffe844b1f685 to your computer and use it in GitHub Desktop.
Save jtsternberg/4a27bb8dffe844b1f685 to your computer and use it in GitHub Desktop.
Add custom post endpoints and misc. functionality
<?php
/**
* Handly place to define our endpoints all in one spot
* @return array Array of our endpoints
*/
function prefix_custom_endpoints() {
return array(
'portfolio',
'testimonials',
'alerts',
'issues',
'reports',
'media',
);
}
/**
* Add the rewrite endpoints
*/
function prefix_add_endpoints() {
foreach ( prefix_custom_endpoints() as $endpoint ) {
add_rewrite_endpoint( $endpoint, EP_PERMALINK );
}
}
add_action( 'init', 'prefix_add_endpoints' );
/**
* Filter the request to make sure our empty
* query vars are actually defined
*
* @param array $q Query params
* @return array Modified query params
*/
function prefix_request_filter( $q ) {
foreach ( prefix_custom_endpoints() as $key ) {
$q[ $key ] = isset( $q[ $key ] );
}
return $q;
}
add_filter( 'request', 'prefix_request_filter' );
/**
* Add a body class for each endpoint
*
* @param array $classes Array of body classes
* @return array Modified array of body classes
*/
function prefix_add_endpoint_body_class( $classes ) {
// If endpoint, add class
if ( $endpoint = prefix_active_endpoint() ) {
$classes[] = 'endpoint-' . $endpoint;
}
return $classes;
}
add_filter( 'body_class', 'prefix_add_endpoint_body_class' );
/**
* Easily check what endpoint you are on
*
* @param string $endpoint (optional) An endpoint to check if you are on a specific endpoint
* @return bool|string If checking a specific endpoint, return will be bool, otherwise will return the name
*/
function prefix_active_endpoint( $endpoint = null ) {
$post_types_with_endpoint = array( 'page' );
// If we are not on an endpoint post_type, bail
if ( ! in_array( get_post_type(), $post_types_with_endpoint ) ) {
return false;
}
// Check if a $endpoint was passed
if ( ! is_null( $endpoint ) ) {
// $endpoint will either be true if we are on the $endpoint, or false if we are not or it does not exist
return get_query_var( $endpoint );
} else {
foreach ( prefix_custom_endpoints() as $endpoint ) {
if ( get_query_var( $endpoint ) ) {
return $endpoint;
}
}
}
// If nothing was true, we must be false
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment