Monday, September 5, 2022
HomeWordPress Developmentplugin improvement - get the queried_object of an url

plugin improvement – get the queried_object of an url


For instance I’ve an url for exemple in gutenberg content material that’s like
https://www.exemple.com/my-tax/my-term-name
or
https://www.exemple.com/en/my-rewrite_tax_slug/my-term-name
or
https://www.exemple.com/my-post-name
or
https://www.exemple.com/my-post-type/my-post-name

How am i able to get the equal of the perform $wp_query->get_queried_object() from thes url strings?

The aim of that is I’m growing a bulk editor for polylang translation plugin of gutenberg posts contents. I want to get (hyperlink|src|href) robotically translated from default_language to translations.
However I am unable to discover a dependable approach to get object from url string.
I find out about

get_page_by_path( string $page_path, string $output = OBJECT, string|array $post_type=”web page” ): WP_Post|array|null
or
get_term_by( string $area, string|int $worth, string $taxonomy = ”, string $output = OBJECT, string $filter=”uncooked” ): WP_Term|array|false

However from the url string I am unable to discover a approach to get post_type or taxonomy or to know if I’m in a submit or time period context.

What about taxonomiesor post_types archives hyperlinks? Subsequent chapter.

What I’ve invetigated:
Class WP->parse_request()
makes use of present server url and $wp_rewrite world to get $query_vars

however it’s fairly empty
the results of the subsequent reworked perform is like this:

      "attachment": "",
      "embed": "true"
    } for media
{
      "web page": ""
    }for web page
[]for time period with rewrite

That is my perform:

    public perform parse_request($url,$extra_query_vars=""){
    world $wp_rewrite;

    /**
    * Filters whether or not to parse the request.
    *
    * @since 3.5.0
    *
    * @param bool         $bool             Whether or not or to not parse the request. Default true.
    * @param WP           $wp               Present WordPress surroundings occasion.
    * @param array|string $extra_query_vars Additional handed question variables.
    */
    
    $parsed_url=parse_url($url);
    if(isset($parsed_url['query'])){
        parse_str($parsed_url['query'], $params);
        $get_error=isset($params['error'])?$params['error']:'';
    }else{
        $params=[];
        $get_error="";
    }
    $this->query_vars     = array();
    $post_type_query_vars = array();

    if ( is_array( $extra_query_vars ) ) {
        $this->extra_query_vars = & $extra_query_vars;
    } elseif ( ! empty( $extra_query_vars ) ) {
        parse_str( $extra_query_vars, $this->extra_query_vars );
    }
    // Course of PATH_INFO, REQUEST_URI, and 404 for permalinks.

    // Fetch the rewrite guidelines.
    $rewrite = $wp_rewrite->wp_rewrite_rules();

    if ( ! empty( $rewrite ) ) {
        // If we match a rewrite rule, this can be cleared.
        $error="404";
        $this->did_permalink = true;

        $pathinfo         = '';//isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : ''; //http://www.instance.com/phpinfo.php/PATH_INFO
        record( $pathinfo ) = explode( '?', $pathinfo );
        $pathinfo         = str_replace( '%', '%25', $pathinfo );

    record( $req_uri ) = explode( '?', $url/*$_SERVER['REQUEST_URI'] */);
    $self            = $url;//"/wp-admin/admin-ajax.php"
    //return $self;
    $home_path       = parse_url( home_url(), PHP_URL_PATH );//null=parse_url(https://www.exemple.com,5);
    $home_path_regex = '';
    if ( is_string( $home_path ) && '' !== $home_path ) ^%s

    /*
    * Trim path data from the top and the main house path from the entrance.
    * For path data requests, this leaves us with the requesting filename, if any.
    * For 404 requests, this leaves us with the requested permalink.
    */
    $req_uri  = str_replace( $pathinfo, '', $req_uri );
    $req_uri  = trim( $req_uri, "https://wordpress.stackexchange.com/" );
    $pathinfo = trim( $pathinfo, "https://wordpress.stackexchange.com/" );
    $self     = trim( $self, "https://wordpress.stackexchange.com/" );

    if ( ! empty( $home_path_regex ) ) {
        $req_uri  = preg_replace( $home_path_regex, '', $req_uri );
        $req_uri  = trim( $req_uri, "https://wordpress.stackexchange.com/" );
        $pathinfo = preg_replace( $home_path_regex, '', $pathinfo );
        $pathinfo = trim( $pathinfo, "https://wordpress.stackexchange.com/" );
        $self     = preg_replace( $home_path_regex, '', $self );
        $self     = trim( $self, "https://wordpress.stackexchange.com/" );
    }

    // The requested permalink is in $pathinfo for path data requests and
    // $req_uri for different requests.
    if ( ! empty( $pathinfo ) && ! preg_match( '|^.*' . $wp_rewrite->index . '$|', $pathinfo ) ) {
        $requested_path = $pathinfo;
    } else {
        // If the request uri is the index, clean it out in order that we do not attempt to match it towards a rule.
        if ( $req_uri == $wp_rewrite->index ) {
            $req_uri = '';
        }
        $requested_path = $req_uri;
    }
    $requested_file = $req_uri;

    $this->request = $requested_path;

    // Search for matches.
    $request_match = $requested_path;
    if ( empty( $request_match ) ) {
        // An empty request may solely match towards ^$ regex.
        if ( isset( $rewrite['$'] ) ) {
            $this->matched_rule="$";
            $question              = $rewrite['$'];
            $matches            = array( '' );
        }
    } else {
        foreach ( (array) $rewrite as $match => $question ) {
            // If the requested file is the anchor of the match, prepend it to the trail data.
            if ( ! empty( $requested_file ) && strpos( $match, $requested_file ) === 0 && $requested_file != $requested_path ) {
                $request_match = $requested_file . "https://wordpress.stackexchange.com/" . $requested_path;
            }

            if ( preg_match( "#^$match#", $request_match, $matches ) ||
                preg_match( "#^$match#", urldecode( $request_match ), $matches ) ) {

                if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=$matches[([0-9]+)]/', $question, $varmatch ) ) {
                    // It is a verbose web page match, let's verify to make sure about it.
                    $web page = get_page_by_path( $matches[ $varmatch[1] ] );
                    if ( ! $web page ) {
                        proceed;
                    }

                    $post_status_obj = get_post_status_object( $page->post_status );
                    if ( ! $post_status_obj->public && ! $post_status_obj->protected
                        && ! $post_status_obj->non-public && $post_status_obj->exclude_from_search ) {
                        proceed;
                    }
                }

                // Obtained a match.
                $this->matched_rule = $match;
                break;
            }
        }
    }

    if ( ! empty( $this->matched_rule ) ) {
        // Trim the question of all the pieces as much as the '?'.
        $question = preg_replace( '!^.+?!', '', $question );

        // Substitute the substring matches into the question.
        $question = addslashes( WP_MatchesMapRegex::apply( $question, $matches ) );

        $this->matched_query = $question;

        // Parse the question.
        parse_str( $question, $perma_query_vars );

        // If we're processing a 404 request, clear the error var since we discovered one thing.
        if ( '404' == $error ) {
            unset( $error, $get_error );
        }
    }

    // If req_uri is empty or if it's a request for ourself, unset error.
    if ( empty( $requested_path ) || $requested_file == $self || strpos( $url, 'wp-admin/' ) !== false ) {
        unset( $error, $get_error );

        if ( isset( $perma_query_vars ) && strpos( $url, 'wp-admin/' ) !== false ) {
            unset( $perma_query_vars );
        }

        $this->did_permalink = false;
    }
}

/**
* Filters the question variables allowed earlier than processing.
*
* Permits (publicly allowed) question vars to be added, eliminated, or modified prior
* to executing the question. Wanted to permit customized rewrite guidelines utilizing your personal arguments
* to work, or every other customized question variables you need to be publicly accessible.
*
* @since 1.5.0
*
* @param string[] $public_query_vars The array of allowed question variable names.
*/
$this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );

foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) {
    if ( is_post_type_viewable( $t ) && $t->query_var ) {
        $post_type_query_vars[ $t->query_var ] = $post_type;
    }
}

foreach ( $this->public_query_vars as $wpvar ) {
    if ( isset( $this->extra_query_vars[ $wpvar ] ) ) {
        $this->query_vars[ $wpvar ] = $this->extra_query_vars[ $wpvar ];
    } elseif ( isset( $_GET[ $wpvar ] ) && isset( $_POST[ $wpvar ] ) && $_GET[ $wpvar ] !== $_POST[ $wpvar ] ) {
        wp_die( __( 'A variable mismatch has been detected.' ), __( 'Sorry, you aren't allowed to view this merchandise.' ), 400 );
    } elseif ( isset( $_POST[ $wpvar ] ) ) {
        $this->query_vars[ $wpvar ] = $_POST[ $wpvar ];
    } elseif ( isset( $_GET[ $wpvar ] ) ) {
        $this->query_vars[ $wpvar ] = $_GET[ $wpvar ];
    } elseif ( isset( $perma_query_vars[ $wpvar ] ) ) {
        $this->query_vars[ $wpvar ] = $perma_query_vars[ $wpvar ];
    }

    if ( ! empty( $this->query_vars[ $wpvar ] ) ) {
        if ( ! is_array( $this->query_vars[ $wpvar ] ) ) {
            $this->query_vars[ $wpvar ] = (string) $this->query_vars[ $wpvar ];
        } else {
            foreach ( $this->query_vars[ $wpvar ] as $vkey => $v ) {
                if ( is_scalar( $v ) ) {
                    $this->query_vars[ $wpvar ][ $vkey ] = (string) $v;
                }
            }
        }

        if ( isset( $post_type_query_vars[ $wpvar ] ) ) {
            $this->query_vars['post_type'] = $post_type_query_vars[ $wpvar ];
            $this->query_vars['name']      = $this->query_vars[ $wpvar ];
        }
    }
}

// Convert urldecoded areas again into '+'.
foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy => $t ) {
    if ( $t->query_var && isset( $this->query_vars[ $t->query_var ] ) ) {
        $this->query_vars[ $t->query_var ] = str_replace( ' ', '+', $this->query_vars[ $t->query_var ] );
    }
}

// Do not enable non-publicly queryable taxonomies to be queried from the entrance finish.
if ( ! is_admin() ) {
    foreach ( get_taxonomies( array( 'publicly_queryable' => false ), 'objects' ) as $taxonomy => $t ) {
        /*
        * Disallow when set to the 'taxonomy' question var.
        * Non-publicly queryable taxonomies can't register customized question vars. See register_taxonomy().
        */
        if ( isset( $this->query_vars['taxonomy'] ) && $taxonomy === $this->query_vars['taxonomy'] ) {
            unset( $this->query_vars['taxonomy'], $this->query_vars['term'] );
        }
    }
}

// Restrict publicly queried post_types to people who are 'publicly_queryable'.
if ( isset( $this->query_vars['post_type'] ) ) {
    $queryable_post_types = get_post_types( array( 'publicly_queryable' => true ) );
    if ( ! is_array( $this->query_vars['post_type'] ) ) {
        if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types, true ) ) {
            unset( $this->query_vars['post_type'] );
        }
    } else {
        $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
    }
}

// Resolve conflicts between posts with numeric slugs and date archive queries.
$this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );

foreach ( (array) $this->private_query_vars as $var ) {
    if ( isset( $this->extra_query_vars[ $var ] ) ) {
        $this->query_vars[ $var ] = $this->extra_query_vars[ $var ];
    }
}

if ( isset( $error ) ) {
    $this->query_vars['error'] = $error;
}

/**
* Filters the array of parsed question variables.
*
* @since 2.1.0
*
* @param array $query_vars The array of requested question variables.
*/
$this->query_vars = apply_filters( 'request', $this->query_vars );

/**
* Fires as soon as all question variables for the present request have been parsed.
*
* @since 2.1.0
*
* @param WP $wp Present WordPress surroundings occasion (handed by reference).
*/
do_action_ref_array( 'parse_request', array( &$this ) );
return [$this, $query];

}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments