Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function pm_detect_post($query) {
- global $wpdb, $wp, $wp_rewrite, $wp_filter;
- $permalink_manager_uris = get_option('permalink-manager-uris');
- // Check if the array with custom URIs is set
- if(!(is_array($permalink_manager_uris))) return $query;
- // Used in debug mode & endpoints
- $old_query = $query;
- /**
- * 1. Prepare URL and check if it is correct (make sure that both requested URL & home_url share the same protoocl and get rid of www prefix)
- */
- $request_url = (!empty($request_url)) ? parse_url($request_url, PHP_URL_PATH) : $_SERVER['REQUEST_URI'];
- $request_url = strtok($request_url, "?");
- $http_host = (!empty($_SERVER['HTTP_HOST'])) ? $_SERVER['HTTP_HOST'] : preg_replace('/www\./i', '', $_SERVER['SERVER_NAME']);
- $request_url = sprintf("http://%s%s", str_replace("www.", "", $http_host), $request_url);
- $raw_home_url = trim(get_option('home'));
- $home_url = preg_replace("/http(s)?:\/\/(www\.)?(.+?)\/?$/", "http://$3", $raw_home_url);
- if(filter_var($request_url, FILTER_VALIDATE_URL)) {
- // Check if "Deep Detect" is enabled
- $deep_detect_enabled = 1
- // Sanitize the URL
- // $request_url = filter_var($request_url, FILTER_SANITIZE_URL);
- // Keep only the URI
- $request_url = str_replace($home_url, "", $request_url);
- // Hotfix for language plugins
- if(filter_var($request_url, FILTER_VALIDATE_URL)) {
- $request_url = parse_url($request_url, PHP_URL_PATH);
- }
- $request_url = trim($request_url, "/");
- // Get all the endpoints & pattern
- $endpoints = 'page|feed|embed|attachment|trackback|filter';
- $pattern = "/^(.+?)(?|\/({$endpoints})(?|\/(.*)|$)|\/()([\d]+)\/?)?$/i";
- // Use default REGEX to detect post
- preg_match($pattern, $request_url, $regex_parts);
- $uri_parts['lang'] = false;
- $uri_parts['uri'] = (!empty($regex_parts[1])) ? $regex_parts[1] : "";
- $uri_parts['endpoint'] = (!empty($regex_parts[2])) ? $regex_parts[2] : "";
- $uri_parts['endpoint_value'] = (!empty($regex_parts[3])) ? $regex_parts[3] : "";
- // Allow to filter the results by third-parties + store the URI parts with $pm_query global
- $uri_parts = $pm_query = apply_filters('permalink_manager_detect_uri', $uri_parts, $request_url, $endpoints);
- // Support comment pages
- preg_match("/(.*)\/{$wp_rewrite->comments_pagination_base}-([\d]+)/", $request_url, $regex_parts);
- if(!empty($regex_parts[2])) {
- $uri_parts['uri'] = $regex_parts[1];
- $uri_parts['endpoint'] = 'cpage';
- $uri_parts['endpoint_value'] = $regex_parts[2];
- }
- // Support pagination endpoint
- if($uri_parts['endpoint'] == $wp_rewrite->pagination_base) {
- $uri_parts['endpoint'] = 'page';
- }
- // Stop the function if $uri_parts is empty
- if(empty($uri_parts)) return $query;
- // Get the URI parts from REGEX parts
- $lang = $uri_parts['lang'];
- $uri = $uri_parts['uri'];
- $endpoint = $uri_parts['endpoint'];
- $endpoint_value = $uri_parts['endpoint_value'];
- // Trim slashes
- $uri = trim($uri, "/");
- // Ignore URLs with no URI grabbed
- if(empty($uri)) return $query;
- // Store an array with custom permalinks in a separate variable
- $all_uris = $permalink_manager_uris;
- // Check what content type should be loaded in case of duplicate ("posts" or "terms")
- $duplicates_priority = apply_filters('permalink_manager_duplicates_priority', false);
- if($duplicates_priority !== false) {
- $uri_count = array_count_values($all_uris);
- foreach($uri_count as $duplicated_uri => $count) {
- if($count <= 1) { continue; }
- $duplicates_ids = array_keys($all_uris, $duplicated_uri);
- foreach($duplicates_ids as $id) {
- if($duplicates_priority == 'posts' && !is_numeric($id)) {
- unset($all_uris[$id]);
- } else if($duplicates_priority !== 'posts' && is_numeric($id)) {
- unset($all_uris[$id]);
- }
- }
- }
- }
- // Flip array for better performance
- $all_uris = array_flip($all_uris);
- // Attempt 1.
- // Find the element ID
- $element_id = isset($all_uris[$uri]) ? $all_uris[$uri] : false;
- // Atempt 2.
- // Decode both request URI & URIs array & make them lowercase (and save in a separate variable)
- if(empty($element_id)) {
- $uri = strtolower(urldecode($uri));
- foreach($all_uris as $raw_uri => $uri_id) {
- $raw_uri = urldecode($raw_uri);
- $all_uris[$raw_uri] = $uri_id;
- }
- // Convert array keys lowercase
- $all_uris = array_change_key_case($all_uris, CASE_LOWER);
- $element_id = isset($all_uris[$uri]) ? $all_uris[$uri] : $element_id;
- }
- // Atempt 3.
- // Check again in case someone used post/tax IDs instead of slugs
- if($deep_detect_enabled && is_numeric($endpoint_value) && isset($all_uris["{$uri}/{$endpoint_value}"])) {
- $element_id = $all_uris["{$uri}/{$endpoint_value}"];
- $endpoint_value = $endpoint = "";
- }
- // Atempt 4.
- // Check again for attachment custom URIs
- if(empty($element_id) && isset($old_query['attachment'])) {
- $element_id = isset($all_uris["{$uri}/{$endpoint}/{$endpoint_value}"]) ? $all_uris["{$uri}/{$endpoint}/{$endpoint_value}"] : $element_id;
- if($element_id) {
- $endpoint_value = $endpoint = "";
- }
- }
- // Allow to filter the item_id by third-parties after initial detection
- $element_id = apply_filters('permalink_manager_detected_element_id', $element_id, $uri_parts, $request_url);
- // Clear the original query before it is filtered
- $query = ($element_id) ? array() : $query;
- /**
- * 3A. Custom URI assigned to taxonomy
- */
- if(strpos($element_id, 'tax-') !== false) {
- // Remove the "tax-" prefix
- $term_id = intval(preg_replace("/[^0-9]/", "", $element_id));
- // Filter detected post ID
- $term_id = apply_filters('permalink_manager_detected_term_id', intval($term_id), $uri_parts, true);
- // Get the variables to filter wp_query and double-check if taxonomy exists
- $term = get_term($term_id);
- $term_taxonomy = (!empty($term->taxonomy)) ? $term->taxonomy : false;
- // Proceed only if the term is not removed and its taxonomy is not disabled
- if(!$disabled && $term_taxonomy) {
- // Get some term data
- if($term_taxonomy == 'category') {
- $query_parameter = 'category_name';
- } else if($term_taxonomy == 'post_tag') {
- $query_parameter = 'tag';
- } else {
- $query["taxonomy"] = $term_taxonomy;
- $query_parameter = $term_taxonomy;
- }
- $term_ancestors = get_ancestors($term_id, $term_taxonomy);
- $final_uri = $term->slug;
- // Fix for hierarchical terms
- if(!empty($term_ancestors)) {
- foreach ($term_ancestors as $parent_id) {
- $parent = get_term((int) $parent_id, $term_taxonomy);
- if(!empty($parent->slug)) {
- $final_uri = $parent->slug . '/' . $final_uri;
- }
- }
- }
- //$query["term"] = $final_uri;
- $query["term"] = $term->slug;
- //$query[$query_parameter] = $final_uri;
- $query[$query_parameter] = $term->slug;
- } else {
- $broken_uri = true;
- }
- }
- /**
- * 3B. Custom URI assigned to post/page/cpt item
- */
- else if(isset($element_id) && is_numeric($element_id)) {
- // Fix for revisions
- $is_revision = wp_is_post_revision($element_id);
- if($is_revision) {
- $revision_id = $element_id;
- $element_id = $is_revision;
- }
- // Filter detected post ID
- $element_id = apply_filters('permalink_manager_detected_post_id', $element_id, $uri_parts);
- $post_to_load = get_post($element_id);
- $final_uri = (!empty($post_to_load->post_name)) ? $post_to_load->post_name : false;
- $post_type = (!empty($post_to_load->post_type)) ? $post_to_load->post_type : false;
- // Proceed only if the term is not removed and its taxonomy is not disabled
- if(!$disabled && $post_type) {
- $post_type_object = get_post_type_object($post_type);
- // Fix for hierarchical CPT & pages
- if(!(empty($post_to_load->ancestors)) && !empty($post_type_object->hierarchical)) {
- foreach ($post_to_load->ancestors as $parent) {
- $parent = get_post( $parent );
- if($parent && $parent->post_name) {
- $final_uri = $parent->post_name . '/' . $final_uri;
- }
- }
- }
- // Alter query parameters + support drafts URLs
- if($post_to_load->post_status == 'draft' || empty($final_uri)) {
- if(is_user_logged_in()) {
- $query['p'] = $element_id;
- $query['preview'] = true;
- $query['post_type'] = $post_type;
- } else if($post_to_load->post_status == 'draft') {
- $query['pagename'] = '-';
- $query['error'] = '404';
- $element_id = 0;
- } else {
- $query = $old_query;
- }
- } else if($post_type == 'page') {
- $query['pagename'] = $final_uri;
- // $query['post_type'] = $post_type;
- } else if($post_type == 'post') {
- $query['name'] = $final_uri;
- } else if($post_type == 'attachment') {
- $query['attachment'] = $final_uri;
- } else {
- // Get the query var
- $query_var = (!empty($post_type_object->query_var)) ? $post_type_object->query_var : $post_type;
- $query['name'] = $final_uri;
- $query['post_type'] = $post_type;
- $query[$query_var] = $final_uri;
- }
- } else {
- $broken_uri = true;
- }
- }
- /**
- * 5A. Endpoints
- */
- if(!empty($element_id) && (!empty($endpoint) || !empty($endpoint_value))) {
- if(is_array($endpoint)) {
- foreach($endpoint as $endpoint_name => $endpoint_value) {
- $query[$endpoint_name] = $endpoint_value;
- }
- } else if($endpoint == 'feed') {
- $query[$endpoint] = 'feed';
- } else if($endpoint == 'page') {
- $endpoint = 'paged';
- $query[$endpoint] = $endpoint_value;
- } else if($endpoint == 'trackback') {
- $endpoint = 'tb';
- $query[$endpoint] = 1;
- } else if(!$endpoint && is_numeric($endpoint_value)) {
- $query['page'] = $endpoint_value;
- } else {
- $query[$endpoint] = $endpoint_value;
- }
- // Fix for attachments
- if(!empty($query['attachment'])) {
- $query = array('attachment' => $query['attachment'], 'do_not_redirect' => 1);
- }
- }
- /**
- * 6. Set global with detected item id
- */
- if(!empty($element_id)) {
- $pm_query['id'] = $element_id;
- // Make the redirects more clever
- $query['do_not_redirect'] = 1;
- /**
- * Disable canonical redirect
- */
- remove_action('template_redirect', 'redirect_canonical');
- add_filter('wpml_is_redirected', '__return_false', 99, 2);
- add_filter('pll_check_canonical_url', '__return_false', 99, 2);
- remove_action('template_redirect', 'wp_old_slug_redirect');
- }
- }
- return $query;
- }
- add_filter('request', 'pm_detect_post', 0, 1);
Add Comment
Please, Sign In to add comment