在 WooCommerce 类别存档页面上将产品标题显示为特定分隔符

Show product titles to specific delimiter on WooCommerce category archive pages

我的产品标题包含分隔符 |,然后我输入了一些 SEO 关键字。

产品标题示例 Samsung UE55AU7172 | Smart 4K UHD 55

我可以强制 WooCommerce 仅在 产品类别页面 中显示该分隔符之前的产品标题吗?

例如,上述产品类别页面中的产品标题为Samsung UE55AU7172

您可以使用 woocommerce_shop_loop_item_title 操作挂钩来编辑产品类别归档页面上的标题。

所以你得到:

/**
 * Show the product title in the product loop.
 */
function action_woocommerce_shop_loop_item_title() {
    // Returns true when viewing a product category archive
    if ( is_product_category() ) {  
        // Removes a function from a specified action hook.
        remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
        
        // Get the title
        $title = get_the_title();
        
        // String contains a specific word
        if ( strpos( $title, '|' ) !== false ) { 
            // Remove portion of a string after a certain character
            $title = substr( $title, 0, strpos( $title, '|' ) );
        }
        
        // Output
        echo '<h2 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . $title . '</h2>';
    }
}
add_action( 'woocommerce_shop_loop_item_title', 'action_woocommerce_shop_loop_item_title', 9 );

使用它在 WooCommerce 存档/商店/猫页面上应用它。

/**
 * Show the product title in the product loop.
 */
function action_woocommerce_shop_loop_item_title() {
    // Removes a function from a specified action hook.
    remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
    
    // Get the title
    $title = get_the_title();
    
    // String contains a specific word
    if ( strpos( $title, '|' ) !== false ) { 
        // Remove portion of a string after a certain character
        $title = substr( $title, 0, strpos( $title, '|' ) );
    }
    
    // Output
    echo '<h2 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . $title . '</h2>';
}
add_action( 'woocommerce_shop_loop_item_title', 'action_woocommerce_shop_loop_item_title', 9 );

您可以使用下面的代码来实现您想要的

remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title', 10 );
add_action('woocommerce_shop_loop_item_title', 'remove_strings_from_title', 10 );

function remove_strings_from_title() {
    
    $title = get_the_title();
    $title = strstr($title, '|', true);
    if ($title == ""){$title = get_the_title();}
    
    
     echo '<p class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . $title . '</p>';
}

代码进入 functions.php 测试和工作