0

Is it possible to add tags to a post, prior to its creation?

Say if I have a link "/wp-admin/new-post.php?tags=a,b,c,d" and by clicking it, I want to enter the new-post page with the tags already associated with it.

2 Answers 2

0

I tried to use the filter wp_get_object_terms like this:

function add_object_terms($terms, $object_ids, $taxonomies, $args){
    if (isset( $_GET[ 'tags' ]) && str_replace("'","",$taxonomies) == "post_tag") {
        $newterms = explode(",",$_GET['tags']);
        return array_merge($terms, $newterms);
    } else {
        return $terms;
    }
}
add_filter('wp_get_object_terms', 'add_object_terms',1,4);

That doesn't work though, maybe the return value has the wrong format, I didn't look it up, instead I tried another filter like this:

function add_tags($tags_to_edit, $taxonomy){
    if (isset( $_GET[ 'tags' ]) && $taxonomy == 'post_tag') {
        return $_GET['tags'];
    } else {
        return $tags_to_edit;
    }
}
add_filter('terms_to_edit', 'add_tags',1,2);

That works but only if you also use the first filter as well, that's because the second filter won't run if there are no terms to deal with.

0

You can do this with the load-post-new.php and wp_insert_post actions.

So here's our URL format:

/wp-admin/post-new.php?add_tags=foo,bar

First, we hook a function to load-post-new.php and check if add_tags is in the request. If so, we add an action to wp_insert_post:

function wpa_load_post_new(){
    if ( array_key_exists( 'add_tags', $_REQUEST ) ) {
        add_action( 'wp_insert_post', 'wpa_insert_post' );
    }
}
add_filter( 'load-post-new.php', 'wpa_load_post_new' );

Then on our wp_insert_post action, we associate whatever tags were passed with this new post as soon as it's added to the database:

function wpa_insert_post( $post_id ){
    wp_set_post_tags( $post_id, $_REQUEST['add_tags'] );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.