Stickers
Stickers

Reputation: 78786

Filter by custom field 'meta_key', 'meta_value' for archive

I'm using a custom field 'meta_key' => 'author_name' for guest posts (no user profiles), and I manually enter the value of the author name for each post.

Is it possible to filter the 'meta_key' and 'meta_value' as a link to:

example.com/author_name/guest001/ or example.com/?author_name=guest001

and display the posts, so that works very similarly to category, tag, or real author?

Upvotes: 1

Views: 590

Answers (1)

first you need to add the rewrite tag like this:

function createRewriteRules() {
    global $wp_rewrite;

    // add rewrite tokens
    $authorname = '%authorname%';
    $wp_rewrite->add_rewrite_tag($authorname, '(.+?)', 'author-name=');

    $keywords_structure = $wp_rewrite->root . "author-name/$authorname/";
    $keywords_rewrite = $wp_rewrite->generate_rewrite_rules($keywords_structure);

    $wp_rewrite->rules = $keywords_rewrite + $wp_rewrite->rules;
    return $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'createRewriteRules');

then hook generate rules and add your rewrite rule:

function add_rewrite_rules( $wp_rewrite ) 
{
        add_rewrite_rule('^author-name/([^/]*)/?','index.php?page_id=12&author-name=$matches[1]','top');
        //page_id is added hardcoded but you can get the page id using your own code/function
}
add_action('init', 'add_rewrite_rules');

add the variable to query vars:

function query_vars($public_query_vars) {
    $public_query_vars[] = "author-name";
    return $public_query_vars;
add_filter('query_vars', 'query_vars');

and it should work, please use the Developer plugin to inspect your rewrite rules.

Upvotes: 1

Related Questions