2

I currently have WordPress build an XML Sitemap everytime a POST or PAGE is PUBLISHED by using this Action...

add_action("publish_post", "create_news_sitemap");

I am not doing the same process but for a News Sitemap which has different criteria. Such as it can only show post that are no older then 48 hours.

I have my code working but I would like to optimize it slightly.

So when add_action("publish_post", "create_news_sitemap"); is ran, I would like to ONLY run a function is it is a Custom Post Type named news that is Publishing a post.

Is this something that is possible?

when the publish_post action is ran, can I detect which POST_TYPE is setting it into action?

3 Answers 3

7

publish_post will give you a second parameter if you ask for it. Notice the fourth parameter of the add_action call. That is your post object.

function run_on_publish_wpse_100421( $postid, $post ) { 
  if ('news' == $post->post_type) 
    // your code
  }
}
add_action('publish_post','run_on_publish_wpse_100421',1,2);
2

The publish_post action gets the post ID as argument, pass that to get_post_type to find out what type of post it is:

function create_news_sitemap( $post_id ){
    $type = get_post_type( $post_id );
    if( 'news' == $type ){
        // do something
    }
}
add_action("publish_post", "create_news_sitemap");
1

Instead of checking for the post type, you can also use publish_{post_type }. In your case publish_news

function run_on_publish_wpse_100421( $postid, $post ) { 
    // your code
}
add_action('publish_news','run_on_publish_wpse_100421',1,2);
1
  • Good call, i'm aware of this but it appears back in 2013 I wasn't...this is a good method =) +1
    – JasonDavis
    Jan 9, 2015 at 5:25

Your Answer

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

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