• Resolved alexli126

    (@alexli126)


    Hello,

    We are using a plugin to create Woo product tags automatically when the product is published.

    Also, we would like to Auto assign or set those product tags as keywords, we note there are several codesnippts.

    Since I am not coding background, could you please clarify which one will work properly or match the Rankmath now?

    1#

    /**
    * Function to automatically update the focus keyword with the post tags, if no focus keyword is set
    */
    function update_focus_keywords()
    {
    $posts = get_posts(array(
    'posts_per_page' => 100,
    'post_type' => 'post' //replace post with the name of your post type
    ));
    foreach ($posts as $p) {
    $keywords = [];
    if (get_the_tags($p->ID)) {
    foreach ((get_the_tags($p->ID)) as $tag) {
    $keywords[] = strtolower($tag->name);
    }
    if (!get_post_meta($p->ID, 'rank_math_focus_keyword', true)) {
    update_post_meta($p->ID, 'rank_math_focus_keyword', implode(", ", array_unique($keywords)));
    }
    }
    }
    }
    add_action('init', 'update_focus_keywords');

    2

    add_action('init', function() {
    $posts = get_posts(
    [
    'posts_per_page' => 100,
    'post_type' => 'product'
    ]
    );

    foreach ( $posts as $p ) {
    $keywords = [];
    $terms = get_the_terms( $p->ID, 'product_tag' );
    if ( empty( $terms ) ) {
    continue;
    }

    foreach ( $terms as $term ) {
    $keywords[] = strtolower( $term->name );
    }

    if ( ! get_post_meta( $p->ID, 'rank_math_focus_keyword', true ) ) {
    update_post_meta( $p->ID, 'rank_math_focus_keyword', implode( ", ", array_unique( $keywords ) ) );
    }
    }
    } );

    3

    add_action( 'save_post', function( $post_id ) {
    $tags = get_the_tags( $post_id );
    if ( ! empty( $tags ) && ! get_post_meta( $post_id, 'rank_math_focus_keyword', true ) ) {
    $keywords = [];
    foreach ( $tags as $tag ) {
    $keywords[] = strtolower( $tag->name );
    }

    save_post_meta( $post_id, 'rank_math_focus_keyword', implode( ',', array_unique( $keywords ) ) );
    }
    } );

    Please note that we would auto assign tags and set keywords to Woocommerce product but not post.

    If no one above is working for the Rankmath latest version, it would be highly appriecaited if you could correct and clarify a working one code snippet.

    Thanks for support.

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Auto assign tags as keywords’ is closed to new replies.