Home > Net >  How to use function and HTML together in functions.php in WordPress
How to use function and HTML together in functions.php in WordPress

Time:09-27

All I have an issue. Please help I am fresher I need a guide.

I have to use the function to get custom field value and need to set that value in my anchor link. but that print outside the link

// add_action( 'woocommerce_single_product_summary', 'technical_specification_pdf_url', 32 );
function technical_specification_pdf_url (){
    $terms = get_the_terms( $post->ID, 'wc-attibute-class' );
    if ( !empty($terms)) {
            $term = array_pop($terms);
                    $text= get_field('technical_specification_pdf', $term);
                    if (!empty($text)) {
                    echo $text;
                    }
    }
}


//  technical specification
add_action( 'woocommerce_single_product_summary', 'technical_specification_button', 30 );

function technical_specification_button() {
  global $product;
  echo '<a href=".'technical_specification_pdf_url()'.">technical specification</a>';
}

I need a button in Woocommerce single page where I can display the brochure link. My function is working fine just the value doesn't add inside the href tag.

CodePudding user response:

In function technical_specification_pdf_url, you must return the $text to append it in function technical_specification_pdf_url.

Step 1: Update echo $text; to return $text;.

Step 2: Add return null; to function technical_specification_pdf_url to let you know that product doesn't exists technical_specification_pdf_url field.

Step 3: Add if ($url) to check the exists condition, with $url = technical_specification_pdf_url();. Because you are doing it on all products, so you should ignore the other products.

// add_action( 'woocommerce_single_product_summary', 'technical_specification_pdf_url', 32 );
function technical_specification_pdf_url (){
    $terms = get_the_terms( $post->ID, 'wc-attibute-class' );
    if ( !empty($terms)) {
            $term = array_pop($terms);
                    $text= get_field('technical_specification_pdf', $term);
                    if (!empty($text)) {
                       return $text;   // Fix here
                    }
    }

    // return null if doesn't exists technical_specification_pdf field
    return null;
}


//  technical specification
add_action( 'woocommerce_single_product_summary', 'technical_specification_button', 30 );

function technical_specification_button() {
  $url = technical_specification_pdf_url();
  // Add check URL here, if not exists, do nothing
  if ($url) {
    global $product;
    echo "<a href=". $url .">technical specification</a>";
  }
}
  • Related