将wpseo_next_rel_link过滤器应用于特定类别

时间:2016-09-25 14:16:27

标签: wordpress function filter

我在我的网站上使用yoast的wp-seo插件,我只想在特定类别中操作此过滤器。

这是我尝试这样做但不起作用的方式。我怎么能这样做?

add_filter('wpseo_next_rel_link', 'my_custom_rel_next');
function my_custom_rel_next($my_c_next_link) {
    //get the last part of the URL
    $parts = parse_url($url);
    parse_str($parts['query'], $query);
    $page_number_var = $_GET['cpage'];
    $page_number_plus_1_var = $_GET['cpage']+1;
    // get url section ex: "mystars", "studios", etc..
    $segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
    $numSegments = count($segments); 
    $currentSegment = $segments[$numSegments - 1];
    // define links to show
        // define links to show
        $next_link_2_next_pages = '<link rel="next" href="'.get_site_url().'/'.$currentSegment.'/?cpage='.$page_number_plus_1_var.'" />';
        if (is_category(561)) {
        return $next_link_2_page_1;
        }else{
        return 'regular next_link outputted by the plugin'; 
        }
}

1 个答案:

答案 0 :(得分:4)

正确的做法:

add_filter( 'wpseo_head', 'custom_change_wpseo_next' , '20' );
function custom_change_wpseo_next( $link ) {
if ( is_page_template(array('page-1.php', 'page-2.php', 'page-3.php')) ) {
 add_filter( 'wpseo_canonical', '__return_false' );
            if ( class_exists('WPSEO_Frontend') ) {
                    $frontend = WPSEO_Frontend::get_instance();
                    global $wp_query;
      if ( get_query_var('paged') ) {
          $paged = get_query_var('paged');
                            } elseif ( get_query_var('page') ) {
                                $paged = get_query_var('page');
                            } else {
                                $paged = 1;
                                echo '<link rel="canonical" href="'.get_pagenum_link( $paged).'" />' . PHP_EOL;
                                echo '<link rel="next" href="'.get_pagenum_link( $paged +1 ).'" />' . PHP_EOL;  
                            }
                            if ( $paged > 1 ) {
                                    //$link0 = '<meta name="robots" content="noindex,follow"/>' . PHP_EOL;
                                    echo '<link rel="canonical" href="'.get_pagenum_link( $paged).'" />' . PHP_EOL; 
                                    echo '<link rel="prev" href="'.get_pagenum_link( $paged -1 ).'" />' . PHP_EOL;  
                                    echo '<link rel="next" href="'.get_pagenum_link( $paged +1 ).'" />' . PHP_EOL;  
                            }
                    }
}
    echo $link;
}

根据需要进行调整。