gpt4 book ai didi

php - 在 WooCommerce 中获取产品类别和标签术语作为元关键字

转载 作者:行者123 更新时间:2023-12-04 09:56:29 33 4
gpt4 key购买 nike

我一直在使用以下代码将标签和类别用作我的 wordpress 帖子的 META 关键字。

function wcs_add_meta_keywords() {
global $post;
if ( is_single() ) {
$cats = get_the_category( $post->ID );
$tags = get_the_tags( $post->ID );
$keywords = '';
foreach ( $cats as $cat ) {
$keywords .= $cat->cat_name . ", ";
}
foreach ( $tags as $tag ) {
$keywords .= $tag->name . ", ";
}
echo '<meta name="keywords" content="' . $keywords . '" />' . "\n";
}}add_action( 'wp_head', 'wcs_add_meta_keywords' , 2 );

以及使用产品描述作为元描述的以下代码。
function wcs_add_meta_description_tag() {
global $post;
if ( is_single() ) {
$meta = strip_tags( $post->post_content );
$meta = strip_shortcodes( $post->post_content );
$meta = str_replace( array("\n", "\r", "\t"), ' ', $meta );
$meta = mb_substr( $meta, 0, 125, 'utf8' );
echo '<meta name="description" content="' . $meta . '" />' . "\n";
}}add_action( 'wp_head', 'wcs_add_meta_description_tag' , 2 );

但是现在我想在 woocommerce 中为我的产品实现相同的目标。我已经学习并知道 woocommerce 使用分类法,所以我尝试使用 get_terms() 和 product_tag、product_cat 代替 get_the_category 和 get_the_tag。但它不起作用。

任何人都可以帮助正确使用这两个代码的变量。

提前致谢

最佳答案

对于单个帖子(或自定义帖子)上的 WordPress 和 WooCommerce 术语分类法,您可以更好地使用 wp_get_post_terms() ,它允许“字段”参数定位术语“名称”,因此代码将更加紧凑和高效:

对于 WooCommerce 和 Wordpress,您将使用:

add_action( 'wp_head', 'wcs_add_meta_keywords' , 2 );
function wcs_add_meta_keywords() {
// For WordPress single posts with categories and tags
if ( is_single() && ! is_product() ) {
$cats = (array) wp_get_post_terms( get_the_id(), 'category', array('fields' => 'names') );
$tags = (array) wp_get_post_terms( get_the_id(), 'post_tag', array('fields' => 'names') );
}
// For WooCommerce single product (product categories and product tags)
elseif ( is_product() ) {
$cats = (array) wp_get_post_terms( get_the_id(), 'product_cat', array('fields' => 'names') );
$tags = (array) wp_get_post_terms( get_the_id(), 'product_tag', array('fields' => 'names') );
}
if ( ! empty( $cats ) || ! empty( $tags ) ){
echo '<meta name="keywords" content="' . implode( ', ', array_merge( $cats, $tags ) ) . '" />' . "\n";
}
}

对于 WooCommerce 仅使用:
add_action( 'wp_head', 'wcs_add_meta_keywords', 2);
function wcs_add_meta_keywords() {
if ( is_product() ) {
$product_cats = (array) wp_get_post_terms( get_the_id(), 'product_cat', array('fields' => 'names') );
$product_tags = (array) wp_get_post_terms( get_the_id(), 'product_tag', array('fields' => 'names') );
}
if ( ! empty( $product_cats ) || ! empty( $product_tags ) ){
echo '<meta name="keywords" content="' . implode( ', ', array_merge( $product_cats, $product_tags ) ) . '" />' . "\n";
}
}

代码位于您的事件子主题(事件主题)的 functions.php 文件中。测试和工作。

关于php - 在 WooCommerce 中获取产品类别和标签术语作为元关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61909841/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com