【问题标题】:Adding a custom field external link to archives category pages将自定义字段外部链接添加到档案类别页面
【发布时间】:2017-01-25 17:10:31
【问题描述】:

我有一个 woocommerce 网站。首先,我想在管理产品页面上添加一个自定义字段来设置我将在我的档案类别产品页面上使用的 exernal url

此外,我还希望在我的管理产品页面设置元框中拥有此自定义字段。但是我更改了所有档案页面上的链接的代码。

现在我有这段代码没有做我需要的:

remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
add_action( 'woocommerce_before_shop_loop_item', 'mycode_woocommerce_template_loop_product_link_open', 20 );
function mycode_woocommerce_template_loop_product_link_open() {

    $url = 'https://www.some_domain.com/';

    echo '<a href="' . $url . '">';

}

我怎样才能让它只在类别档案页面上工作?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce categories product


    【解决方案1】:

    第 1 步 - 在管理产品页面设置元框中创建自定义字段:

    // Inserting a Custom Admin Field
    add_action( 'woocommerce_product_options_general_product_data', 'add_custom_text_field_create' );
    function add_custom_text_field_create() {
        echo '<div class="options_group">';
    
        woocommerce_wp_text_input( array(
            'type'              => 'text',
            'id'                => 'extern_link',
            'label'             => __( 'External Link', 'woocommerce' ),
            'placeholder'       => '',
            'description'       => __( 'Insert url', 'woocommerce' ),
        ) );
    
        echo '</div>';
    }
    
    // Saving the field value when submitted
    add_action( 'woocommerce_process_product_meta', 'add_custom_field_text_save' );
    function add_custom_field_text_save( $post_id ){
    $wc_field = $_POST['extern_link'];
    if( !empty( $wc_field ) )
        update_post_meta( $post_id, 'extern_link', esc_attr( $wc_field ) );
    } 
    

    第 2 步 - 仅在产品类别存档页面中将链接替换为自定义元值。

    remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open');
    add_action( 'woocommerce_before_shop_loop_item', 'custom_wc_template_loop_product_link_open', 10 );
    function custom_wc_template_loop_product_link_open() {
        // For product category archives pages only.
        if (is_product_category()) {
            // You get here your custom link
            $link = get_post_meta(get_the_ID(), 'extern_link', true);
            echo '<a href="' . $link . '" class="woocommerce-LoopProduct-link">';
        //For the other woocommerce archives pages
        } else {
            echo '<a href="' . get_the_permalink() . '" class="woocommerce-LoopProduct-link">';
        }
    }
    

    代码位于您的活动子主题(或主题)的 function.php 文件中或任何插件文件中。

    此代码已经过测试并且可以工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多