使用Yoast SEO插件设置主要类别

时间:2018-09-19 作者:Dylan Smit

function set_primary_on_publish ($post_id) {
    global $post; 

    $categories = get_the_terms( $post->ID, \'category\' ); 
    // wrapper to hide any errors from top level categories or products without category
    if ( $categories && ! is_wp_error( $category ) ) : 

        // loop through each cat
        foreach($categories as $category) :
          // get the children (if any) of the current cat
          $children = get_categories( array (\'taxonomy\' => \'category\', \'parent\' => $category->term_id ));

          if ( count($children) == 0 ) {

                $childid = $category->term_id;
                update_post_meta($post->ID,\'_yoast_wpseo_primary_category\',$childid);

          }
        endforeach;

    endif;

    }
add_action( \'save_post\', \'set_primary_on_publish\', 10, 2 );
add_action( \'edit\', \'set_primary_on_publish\', 10, 2 );
add_action( \'wp_insert_post\', \'set_primary_on_publish\', 10, 2 );
我正试图将最深的子类别保存为Yoast SEO插件中的主要类别,但上述内容似乎没有起到作用。

有人能帮我吗?

向你问好,Dylan Smit

2 个回复
SO网友:Sergey Harchevnikov

改为尝试

update_post_meta($post->ID,\'_yoast_wpseo_primary_category\',$childid); 
使用以下功能:

function wpseoPrimaryTerm($taxonomy, $postID, $term){

  if ( class_exists(\'WPSEO_Primary_Term\') ) {
  // Set primary term.
  $primaryTermObject = new WPSEO_Primary_Term($taxonomy, $postID);
  $primaryTermObject->set_primary_term($term);

  // Save primary term.
  $primaryTermObjectAdmin = new WPSEO_Primary_Term_Admin();
  $primaryTermObjectAdmin->save_primary_terms($postID);
  }else{
    echo \'Class WPSEO does not exit\';
  }
}
在哪里$taxonomy - taxonomy name, $PostID - $post->ID, $term - $childid

SO网友:Chris

你需要改变productproduct_cat_yoast_wpseo_primary_category_yoast_wpseo_primary_product_cat 让它发挥作用。在保存或更新产品时,它将抓住最深的product_id 并将其设置为product_idwp_postmeta 桌子

function set_primary_on_publish ($post_ID) {
    global $post;

    $categories = get_the_terms( $post->ID, \'product_cat\' ); 

    // wrapper to hide any errors from top level categories or products without category
    if ( $categories && ! is_wp_error( $category ) ) :

        // loop through each cat
        foreach($categories as $category) :

          // get the children (if any) of the current cat
          $children = get_categories( array (\'taxonomy\' => \'product_cat\', \'parent\' => $category->term_id ));

          if ( count($children) == 0 ) {
                $childid = $category->term_id;
                update_post_meta($post->ID,\'_yoast_wpseo_primary_product_cat\',$childid);
          }
        endforeach;
    endif;
}

结束

相关推荐

如何在用户单击按钮时使用AJAX调用PHP函数

我正在开发一个使用自定义模板/主题的wordpress网站,但我遇到了麻烦。我想使用Ajax在用户单击按钮时调用函数。在一个页面上,我有一个这样的按钮:<p class=\'form-submit\'> <input name=\'message_read\' type=\'submit\' class=\'submit button mark-as-read\' value= \'Mark as read\' /> </p>&#