我已将一个函数挂接到一个名为\'job_manager_check_for_expired_jobs\'
, 我希望它基于变量的值运行$create_sitemap
. 默认情况下,该值为true,但可以通过过滤器进行更改。
问题是,如果我使用该站点,然后将过滤器更改为false,那么钩子仍会像变量为true一样运行,因此操作不会被删除。
我使用的代码在这里,任何帮助都将不胜感激!
// Check the WPJM plugin exists
if( is_plugin_active( \'wp-job-manager/wp-job-manager.php\') ){
// Generate sitemap by default
$create_sitemap = true;
// Add filter so that users turn off the sitemap generation if they want
if( has_filter(\'sitemap_filter_func\') ) {
$create_sitemap = apply_filters(\'sitemap_filter_func\', $create_sitemap);
}
// If we want to ping Google
if( $create_sitemap == true ){
// Create the CRON job
add_action( \'job_manager_check_for_expired_jobs\', \'generate_sitemap\' );
} else {
// Remove the CRON job to update the sitemap
remove_action( \'job_manager_check_for_expired_jobs\', \'generate_sitemap\' );
}
}
function generate_sitemap() {
$sitemap = \'<?xml version="1.0" encoding="UTF-8"?>\';
$sitemap .= \'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\';
// Get a query of all jobs that are available
$all_jobs = new WP_Query( array( \'post_type\' => \'job_listing\', \'post_status\' => \'publish\', \'posts_per_page\' => -1 ) );
// Add the URL and last modified time (in GMT) to the sitemap
foreach( $all_jobs->posts as $post ){
$sitemap .= \'<url>\';
$sitemap .= \'<loc>\' . get_the_permalink( $post->ID ) . \'</loc>\';
$sitemap .= \'<lastmod>\' . date( \'c\', strtotime( $post->post_modified_gmt ) ) . \'</lastmod>\';
$sitemap .= \'</url>\';
}
$sitemap .= \'</urlset>\';
// Write the sitemap to yoursite.com/job-sitemap.xml
$fp = fopen(ABSPATH . \'job-sitemap.xml\', \'w\');
fwrite($fp, $sitemap);
fclose($fp);
}
使用的过滤器示例:
add_filter( \'sitemap_filter_func\', \'hide_the_sitemap\');
function hide_the_sitemap( $create_sitemap ){
return false;
}
SO网友:Junaid
我不知道为什么remove_action
不起作用,因为从代码的外观来看,它应该起作用。或者,您可以将条件逻辑添加到generate_sitemap()
function generate_sitemap() {
global $create_sitemap;
if ( $create_sitemap ) return false;
$sitemap = \'<?xml version="1.0" encoding="UTF-8"?>\';
$sitemap .= \'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\';
// Get a query of all jobs that are available
$all_jobs = new WP_Query( array( \'post_type\' => \'job_listing\', \'post_status\' => \'publish\', \'posts_per_page\' => -1 ) );
// Add the URL and last modified time (in GMT) to the sitemap
foreach( $all_jobs->posts as $post ){
$sitemap .= \'<url>\';
$sitemap .= \'<loc>\' . get_the_permalink( $post->ID ) . \'</loc>\';
$sitemap .= \'<lastmod>\' . date( \'c\', strtotime( $post->post_modified_gmt ) ) . \'</lastmod>\';
$sitemap .= \'</url>\';
}
$sitemap .= \'</urlset>\';
// Write the sitemap to yoursite.com/job-sitemap.xml
$fp = fopen(ABSPATH . \'job-sitemap.xml\', \'w\');
fwrite($fp, $sitemap);
fclose($fp);
}
确保
$create_sitemap
可在函数中访问。