【问题标题】:Custom Page Titles and Descriptions on WooCommerce Category PagesWooCommerce 类别页面上的自定义页面标题和描述
【发布时间】:2020-04-18 18:32:35
【问题描述】:

我已使用高级自定义字段在我的所有页面、帖子、类别和产品上添加自定义页面标题字段。

为了删除默认的<title> 标签并确保该字段正确通过,我在我的functions.php 文件中使用了以下函数:

/* Remove Default <title> tag */

remove_action( 'wp_head', '_wp_render_title_tag', 1 );


// Add new <title> and description tags 

function child_theme_head_script() { ?>
  <title><?php the_field('seo_page_title'); ?></title>
  <meta name="description" content="<?php the_field('seo_page_description'); ?>"/>
  <!-- Your HTML goes here -->
<?php }
add_action( 'wp_head', 'child_theme_head_script' );

除了我的类别页面之外,这在整个网站上都可以正常工作:http://staging.morningsidepharm.com/products/branded-medicines

在分类页面上,它似乎取自页面上出现的第一个产品的标题...对于上面的页面,页面标题显示为:Bimizza(去氧孕烯炔雌醇)片剂品牌药|晨兴制药

而不仅仅是:品牌药 |晨兴制药

我认为函数中的wp_head 会针对所有 Wordpress 页面的头部,然后删除标题标签并添加自定义标签...实际上似乎这样做是正确的,但它只是从第一个产品,而不是来自该类别。该类别看起来像这样有什么帮助:

其中的SEO文件,分别对应:&lt;?php the_field('seo_page_title'); ?&gt;&lt;?php the_field('seo_page_description'); ?&gt;

谁能指出我正确的方向?我不确定我哪里出错了......

** 更新 ** ** 更新 **

我已经尝试过这个,但它似乎没有效果......

/* Remove Default <title> tag */

remove_action( 'wp_head', '_wp_render_title_tag', 1 );


// Add new <title> and description tags 

$term = get_queried_object();
$title = get_field('seo_page_title', $term);
$desc = get_field('seo_page_description', $term);

function child_theme_head_script() { ?>
  <title><?php echo $title; ?></title>
  <meta name="description" content="<?php echo $desc; ?>"/>
  <!-- Your HTML goes here -->
<?php }
add_action( 'wp_head', 'child_theme_head_script' );

【问题讨论】:

    标签: php wordpress advanced-custom-fields


    【解决方案1】:

    the_field() 只能在循环中使用,这就是它这样做的原因,因为它从当前循环项中提取数据。如果您想定位分类的字段,则需要将对该分类的引用传递给函数。

    我会建议这样的事情:

    $term = get_queried_object();
    the_field('seo_page_title', $term);
    

    这是 ACF 文档中的相关页面:https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/

    【讨论】:

    • 非常感谢,彼得,我想我明白了 - 我在页面上显示它们时已经处理过类似的事情,但由于这是在函数文件中,我不确定正确的语法。 ..我已经用我根据您的建议尝试过的东西更新了我的问题,但这似乎没有任何影响......另外,如果这确实有效,这对普通页面仍然有效吗?还是我必须同时使用原始代码和这段新代码?
    • 我实际上认为我可以通过在实际函数内部而不是外部添加术语信息来使其工作!很快就会更新...
    • 这似乎根据您的建议工作 - 随时将其添加到您的答案中:) /* 删除默认 标签 */ remove_action( 'wp_head', '_wp_render_title_tag', 1 );函数 child_theme_head_script() { ?> <?php $term = get_queried_object(); $title = get_field('seo_page_title', $term); $desc = get_field('seo_page_description', $term); ?><title><?php echo $title; ?>
    猜你喜欢
    • 1970-01-01
    • 2019-05-21
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 2016-07-10
    相关资源
    最近更新 更多