PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 28, 2021

[FIXED] Why Wordpress post_name is returning multiple values?

 December 28, 2021     php, wordpress     No comments   

Issue

I'm trying to get the current page slug by using get_post_field( 'post_name', get_post() ), however, this is returning multiple values.

My code looks like this (I'm writing this in a custom plugin):

function prefix_filter_query( $query_string, $grid_id, $action ) {

    // If the content is not filtered on first render.
    if ( 'render' === $action && empty( $query_string ) ) {
        $slug = get_post_field( 'post_name', get_post() );
        
        $query_string = [
            'categories' => [ $slug ]
        ];
    
        _error_log($slug);
    }
    
    return $query_string;
    
}

function _error_log ($value) {
    error_log(print_r($value, true), 3, __DIR__ . '/log.txt');
    error_log("\r\n\r\n", 3, __DIR__ . '/log.txt');
}

add_filter( 'wp_grid_builder/facet/query_string', 'prefix_filter_query', 10, 3 );

The log is showing first the current page (here a category, like 'hoodies'), and then the homepage slug of my website, like this :

hoodies

home

I understood that home was showed because I set the home page of my website to be the static default homepage. I tried to disable it and see if it solved my issue but then the second value returned by the log was just an empty space:

hoodies


I want to get only hoodies and I don't understand why there's a second value, whether it is home or an empty value.

To give a bit of context, I'm using a filter plugin for products in an e-commerce website and the plugin is giving a built-in function to filter the content before it is rendered. https://docs.wpgridbuilder.com/resources/filter-facet-query-string/ Another interesting fact, in our example, hoodies will successfully filter the grid of items to show only hoodies but the query in the URL will be ?_categories=home.

Solution found 28/12/2021

I got an answer from the plugin support (WP Grid Builder) and the issue was that my code was incompatible with the Ajax requests made by WP Grid Builder. Here's the solution I was provided:

add_filter(
    'wp_grid_builder/facet/query_string',
    function( $query_string, $grid_id, $action ) {

        global $post;


        if ( 'render' === $action && empty( $query_string ) ) {

            $referer   = wp_get_referer();
            $post_id   = wp_doing_ajax() ? url_to_postid( $referer ) : $post->ID;
            $post_slug = get_post_field( 'post_name', $post_id );

            $query_string = [
                'categories' => [ $post_slug ],
            ];

        }

        return $query_string;

    },
    10,
    3
);

Solution

Are you just trying to get the current page slug ? You could go through the server request uri $_SERVER['REQUEST_URI']:

PHP >= 8.0.0

<?php

/**
 * Retrieve the current page slug.
 * 
 * @return String The current page slug.
 */
if ( ! function_exists( 'get_the_current_slug' ) ) {

    function get_the_current_slug() {

        $url = $_SERVER['REQUEST_URI'];

        if ( str_contains( $url, '?' ) ) {
        
            $url = substr( $url, 0, strpos( $url, '?' ) );
        
        };
        
        $slugs = ( str_ends_with( $url, '/' ) ? explode( '/', substr( $url, 1, -1 ) ) : explode( '/', substr( $url, 1 ) ) );
        
        return end( $slugs );

    };

};

PHP < 8.0.0 (eg: 7.x.x)

<?php

/**
 * Checks if a string ends with a given substring.
 * 
 * @param String $haystack The string to search in.
 * @param String $needle The substring to search for in the haystack.
 * 
 * @return Integer < 0 if haystack from position offset is less than needle, > 0 if it is greater than needle, and 0 if they are equal. If offset is equal to (prior to PHP 7.2.18, 7.3.5) or greater than the length of haystack, or the length is set and is less than 0, substr_compare() prints a warning and returns false.
 * 
 * @see https://www.php.net/manual/en/function.substr-compare.php
 */
if ( ! function_exists( 'startsWith' ) ) {

    function startsWith( $haystack, $needle ) {

        return substr_compare( $haystack, $needle, 0, strlen( $needle ) ) === 0;

    };

};

/**
 * Retrieve the current page slug.
 * 
 * @return String The current page slug.
 */
if ( ! function_exists( 'get_the_current_slug' ) ) {

    function get_the_current_slug() {

        $url = $_SERVER['REQUEST_URI'];

        if ( strpos( $url, '?' ) !== false ) {

            $url = substr( $url, 0, strpos( $url, '?' ) );

        };

        $slugs = ( startsWith( $url, '/' ) ? explode( '/', substr( $url, 1, -1 ) ) : explode( '/', substr( $url, 1 ) ) );

        return end( $slugs );

    };

};

On the front end:

<?php

echo get_the_current_slug();


Answered By - amarinediary
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing