• I have the following in order to filter by ID (I have a specific column for post ID):

    /**
    * Add search custom posts by their ID in WordPress dashboard
    *
    */
    add_action( 'parse_request', 'cdxn_search_by_id' );
    function cdxn_search_by_id( $wp ) {
        global $pagenow;
        if( !is_admin() && 'edit.php' != $pagenow && 'post' !== $_GET['post_type']) {
    		return;
    	}
            
        // If it's not a search return
        if( !isset( $wp->query_vars['s'] ) ) {
    		return;
    	}
    

    How can I modify this function (or create another one) in order to search by meta key “function_name” ? I dont need the exact match, i.e. if I digit “bellarosa” I’ll list both “bellarosa c7” and “bellarosa c72”

    The page I need help with: [log in to see the link]

Viewing 15 replies - 1 through 15 (of 37 total)
  • Moderator bcworkz

    (@bcworkz)

    Use the “pre_get_posts” action hook. You can get the search term in a similar manner: $query->get_query_var('s'). Use it in a “meta_query” arg you’d set, specifying “LIKE” as the comparison operator (keyed “meta_compare”).

    Doc page:
    https://developer.www.ads-software.com/reference/classes/wp_query/
    Locate “Custom Field (post meta) Parameters” in the Table of Contents and follow that link. (direct linking to this section from here doesn’t work well on this page)

    Thread Starter sacconi

    (@sacconi)

    A thing like that?

    $args = array(
        'meta_key' => 'function name',
        'meta_compare' => 'like',
    );
     
    $q = new WP_Query( $args );
    Moderator bcworkz

    (@bcworkz)

    Yes, sort of, but you also need a “meta_value” arg to compare against. And 'like' needs to be upper case: 'LIKE'.

    In my earlier reply I mentioned “meta_query”. That’s an option if you require more complex query logic with custom fields. But I confused “meta_compare” here with “compare” as used with “meta_query”. You managed to get the right idea despite my confusing reply.

    Thread Starter sacconi

    (@sacconi)

    meta_value will be the name I’ll introduce in the search box, not a specific value, each apartment has his own name, there are hundreds, how can I declare it?

    Moderator bcworkz

    (@bcworkz)

    Get it from where ever the search term ends up in PHP and use it as one of the query args. If it’s the typical WP search box, it’ll be in the query var “s”. Then you can do something similar to:
    'meta_value' => $query->get_query_var('s'),

    At least if you were making a new query object like in your suggested code. I’d forgotten the context of this topic in my last reply agreeing with your suggested code. Setting the query’s args like that is correct, but you wouldn’t create a new query object from a “pre_get_posts” callback. You’ll want to modify the current query. More like this (untested):

    add_action('pre_get_posts', 'search_like_meta');
    function search_like_meta( $query ) {
    	if ( ! is_admin() && $query->is_main_query() ) {
    		if ( $query->is_search()) {
    			$query->set('meta_value', $query->get('s'));
                            $query->set('meta_key', 'function_name');
                            $query->set('meta_compare', 'LIKE');
    
                            //convert from search functionality to archive
                            $query->set('s', '');
                            $query->is_search == false;
                            $query->is_archive == true;
    		}
    	}
    }

    You may need to set other query vars to get the results you want.

    Thread Starter sacconi

    (@sacconi)

    Unluckily this is not working ??

    Moderator bcworkz

    (@bcworkz)

    There’s something else about your search query that’s off then. I tested my code on my site, changing meta_key to what works on my site. The code works as expected. Finds all published posts, pages, and attachments that have the search term within their respective postmeta fields for the specified key.

    You could use the Query Monitor plugin to see what SQL is used for the query. Filter the queries by caller for Main Query. It should look more or less like:

    SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
    FROM wp_posts
    INNER JOIN wp_postmeta
    ON ( wp_posts.ID = wp_postmeta.post_id )
    WHERE 1=1
    AND ( ( wp_postmeta.meta_key = 'function_name'
    AND wp_postmeta.meta_value LIKE '%search-term%' ) )
    AND ((wp_posts.post_type = 'post'
    AND (wp_posts.post_status = 'publish'
    OR wp_posts.post_status = 'private'))
    OR (wp_posts.post_type = 'page'
    AND (wp_posts.post_status = 'publish'
    OR wp_posts.post_status = 'private'))
    OR (wp_posts.post_type = 'attachment'
    AND (wp_posts.post_status = 'publish'
    OR wp_posts.post_status = 'private')))
    GROUP BY wp_posts.ID
    ORDER BY wp_posts.post_date DESC
    LIMIT 0, 10

    Examine your query to determine what it is about it that prevents it from working as expected. Whatever it is, it can likely be fixed via the “pre_get_posts” action.

    Thread Starter sacconi

    (@sacconi)

    I give a better explanation abot what doesnt work. I have in the name columns the following apartments all containing “Nashira”: Nashira C8H, Nashira C8B, Nashira C8, Nashira c7x and Nashira c7. If I put “Nashira” in the search box all the apartments should be in the results, on the contrary I get only”Nashira c7x”, and If I put in the search box “Nashira c7x” nothing is done as result!. Other one word name give nothing as result. If I write “Aloe”, no match (but there is one), and so on. The name of the apartments can be composed by 2 or more words (or even numbers)

    Moderator bcworkz

    (@bcworkz)

    Name column? As in post_name of the wp_posts DB table? Also know as post slug. Or do you mean the “function_name” meta key? There’s no formal DB column for that, so I’m a little confused. Post slugs wouldn’t have a space nor uppercase, but meta data could.

    My suggested code only searches for search terms within the meta_value column keyed by “function_name”. If you include a space in the search term, it is not broken into two terms as is often done. The entire string has to match, space included. Letter case should not matter.

    All I can say for sure is my code works with a key name that exists in my DB and which has related data that matches the search term. Obviously we do not have the same data in our respective DBs. The best way to see why it’s not working for you is to examine the SQL being used with the Query Monitor plugin. There is some clause in the SQL that’s preventing posts from being returned which you think should be returned.

    With Query Monitor, after making an unsuccessful search, click the timing data in the admin bar. In the query panel go to Database Queries. Filter for caller Main Query. Post the SQL query here if you need help interpreting it.

    Thread Starter sacconi

    (@sacconi)

    I mean this column: https://ibb.co/P49XPFt

    When I edit a post the name (nome) of the apartment corresponds to the meta key “function_name”, so the name is the value of the function_name

    Thread Starter sacconi

    (@sacconi)

    I tryed with Query Monitor with the name “Aloe”, here are the results: https://ibb.co/xYfqmJK

    Thread Starter sacconi

    (@sacconi)

    Another try with Query monitor, name “Nashira”, I have just one result but I should get 5 results: Nashira C8H, Nashira C8B, Nashira C8, Nashira c7x and Nashira c7, I get only Nashira c7x

    https://ibb.co/DCmB6qj

    Thread Starter sacconi

    (@sacconi)

    Another try with Query Monitor. I insert name “Agneza 1” and get “Agneza 2”: https://ibb.co/pxHktLH

    Moderator bcworkz

    (@bcworkz)

    Your column is in a customized list table. What column from a DB table does “Name” come from? post_title in wp_posts? Are all these apartments regular WP “post” post type? Not a custom post type?

    The queries are not looking at “function_name” meta at all. The code I suggested is inactive. Query is looking in post_title, post_content, or post_excerpt only.

    How big is you DB? The query is kind of slow to execute. To be fair, search queries are horribly inefficient.

    Thread Starter sacconi

    (@sacconi)

    Post type=post, not custom posts; about “function_name” I created a custom field in the post editor page, I put here the code, if it can help:

    add_action( 'add_meta_boxes_post', "name_add_meta_box" );
    
    /*
     * Routine to add a meta box.  Called via a filter hook once WordPress is initialized
     */
    function name_add_meta_box(){
        add_meta_box(
            "name_meta_box",  // An ID for the Meta Box.  Make it unique to your plugin
            __( "Nome", 'textdomain' ),  // The title for your Meta Box
            "name_meta_box_render",  // A callback function to fill the Meta Box with the desired UI in the editor
            "post",  // The screen name - in this case the name of our custom post type
            "side"  // The context or placement for the meta box.  Choose "normal", "side" or "advanced"
        );
    }
    
    /*
     * Routine to display a custom meta box editor
     * Note: In this example our custom meta data is saved as a row in the postmeta database table.
     * $post PostObject An object representing a WordPress post that is currently being loaded in the post editor.
     */
    function name_meta_box_render( $post ){
    
        // Get the name and display it in a text field
        $name = get_post_meta( $post->ID, "function_name", true );
        echo '<div><input type="text" name="function_name" value="'.$name.'" placeholder="Nome" /></div>';
      
    }
    
    // Hook into the save routine for posts
    add_action( 'save_post', 'name_meta_box_save');
    
    /*
     * Routine to save the custom post meta data from the editor
     * Note: We retrieve the form data through the PHP Global $_POST
     * $post_id int The ID of the post being saved
     */
    function name_meta_box_save( $post_id ){
         
        // Check to see if this is our custom post type (remove this check if applying the meta box globally)
        if($_POST['post_type'] == "post"){
            
            // Retrieve the values from the form
            $name = $_POST['function_name'];
            
    
            // Clean, sanitize and validate the input as appropriate
    
            // Save the updated data into the custom post meta database table
            update_post_meta( $post_id, "function_name", $name );
            
    
        }     
    }
    
Viewing 15 replies - 1 through 15 (of 37 total)
  • The topic ‘search on posts table by function_name’ is closed to new replies.