Search code examples
phpwordpressshortcodewordpress-shortcode

WordPress shortcode for custom post types


I am working on a custom WordPress theme and need to call the $title field for each page within the footer. That field needs to be the same as the one I set as SEO title with the RankMath plugin and I solved it using this function:

add_shortcode('rm_title', 'rm_shortcode_title');
function rm_shortcode_title(){
    global $post;
    $title = get_post_meta($post->ID, 'rank_math_title', true);
    return $title;
}

Now, using the shortcode [rm_title] I can see the SEO title within the footer. However, this only works for classic post types (pages and posts).

What I am trying to do is to also use this shortcode for custom post types, in particular on post_type=user_ads. I've noticed that when I go into the edit screen, in addition to the post_type, there are several fields in the url. I list them here:

  1. taxonomy=custom_5662
  2. tag_ID=480 ( this value changes for each post type )
  3. post_type=user_ads

The complete editing url of the individual custom post types has this structure: https://localhost/wp-admin/term.php?taxonomy=custom_5662&tag_ID=XXX&post_type=user_ads

I have tried various ways without ever being able to find a working solution, so I am kindly asking for help.

Thank you in advance for reading this.


Solution

  • As noted in the comments, based on the URL for editing this is a taxonomy and not a CPT, and as such the meta is stored in a different location.

    To be more generic, instead of using the global $post object we can ask WordPress for the current "thing" using get_queried_object(). This can return several different things depending on the URL but we are (currently) only interested in posts and taxonomy terms. From that we can perform and instance of test and return the appropriate data.

    add_shortcode('rm_title', 'rm_shortcode_title');
    function rm_shortcode_title(){
        $obj = get_queried_object();
        if($obj instance of WP_Post){
            return get_post_meta($obj->ID, 'rank_math_title', true);
        }
    
        if($obj instance of WP_Term){
            return get_term_meta($obj->term_id, 'rank_math_title', true);
        }
    }
    

    As noted, there's other things that might be queried that you might be interested in, too. For instance, get_queried_object() might return a WP_User object on author pages if you are using those, and if so you'd want to use get_user_meta.

    It can also return a WP_Post_Type object on archive pages, however that doesn't have a direct get_XYZ_meta function, and instead, if your plugin supports it, it is probably somewhere in the options table.

    Also, I have no idea if you term code actually works. You might need to run var_dump(get_term_meta($obj->term_id)); with only one parameter to see what is really in the table for that object.