wordpress hook is not firing

billybadass

I've read and tried a lot before posting this.

I have a custom sitemap function that I want to trigger on update/create/save post. I've tried to create new post, update an existing one and just save for the following hooks:

save_post
acf/save_post
pre_post_update
edit_post
the_post
publish_post

Nothing of the above works. I unit tested the function and it does work when hooked on init and admin_init. So I know it's a hook problem. Any advice would be highly appreciated.

All the code:

function pull_active_pages(){
    global $wpdb;
    $query = $wpdb->get_results(" SELECT * FROM `wp_posts` WHERE (`post_type` LIKE 'page' OR `post_type` LIKE 'post') AND `post_status` LIKE 'publish';  ", OBJECT);
    return $query;
}

function makeSitemap(){
    $file = 'sitemap.xml';  //that means in the root, provide full path
    $query = pull_active_pages();
    $output = '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
    $output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-news/0.9 http://www.google.com/schemas/sitemap-news/0.9/sitemap-news.xsd">'.PHP_EOL;
    foreach((array)$query as $record){
        $output .= '<url>'.PHP_EOL; 
        $url = get_permalink($record->ID);
        $output .= '<loc>' . $url . '</loc>'.PHP_EOL;
        $last_mod = $record->post_modified_gmt;
        $output .= '<lastmod>' . $last_mod .'</lastmod>'.PHP_EOL;
        $output .= '<priority>1.00</priority>'.PHP_EOL;
        $output .= '</url>'.PHP_EOL;
    }
    $flags = FILE_APPEND; //redo the whole thing no append for now
    $output .='</urlset>';
    file_put_contents( $file, $output);
}

add_action('save_post',  function(){ makeSitemap();}, 10, 2);
Nick P.

You should change the action like that

add_action('save_post', 'makeSitemap');

and add absolute path to the filename

$file = ABSPATH . '/sitemap.xml';  //that means in the root, provide full path

Check this https://wpengineer.com/2382/wordpress-constants-overview/#ABSPATH for other absolute paths constants

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related