target=_Blank in this php code

Hope you’re all well.

So here’s what I want to do. I want to add to a review plugin in wordpress the possibility to open the page I want in a new window with the target=”_blank” code.

Read More

I believe that’s where the magic is happening, this is the original:

if ($show_morelink != '') {
                $review->review_text .= " <a href='".$this->get_jumplink_for_review($review,1)."'>$show_morelink</a>";
            }

This is what I did without any success:

if ($show_morelink != '') {
                $review->review_text .= " <a href='".$this->get_jumplink_for_review($review,1)."' target="_blank">$show_morelink</a>";
            }

I’m a beginner in PHP and I hope that someone can help me with this… I know it’s not so hard.. I’m just missing something.

Thanks!

Related posts

Leave a Reply

5 comments

  1. You must escape your quotes.

    Use the following

        $_morelink != '') {
            $review->review_text .= "<a href='".$this->get_jumplink_for_review($review,1)."' target="_blank">$show_morelink</a>";
        }
    

    Source for handling strings.

  2. Because your code is surrounded with double quotes, you are breaking out of them when you add in the target. You can either escape the quotes like this using a slash:

    $review->review_text .= " <a href='".$this->get_jumplink_for_review($review,1)."' target="_blank">$show_morelink</a>";
    

    Or change to using single quotes:

    $review->review_text .= " <a href='".$this->get_jumplink_for_review($review,1)."' target='_blank'>$show_morelink</a>";
    

    Edit
    A third way you could do it is surrounding the whole string in single quotes and remove the single quotes and periods form inside:

    $review->review_text .= ' <a href="$this->get_jumplink_for_review($review,1)" target="_blank">$show_morelink</a>';
    
  3. Your problem is that you’re using doublequotes to denote php strings, so you can’t use doublequotes for your html:

    if ($show_morelink != '') {
        $review->review_text .= " <a href='".$this->get_jumplink_for_review($review,1)."' target='_blank'>$show_morelink</a>";
    }
    

    If you look at the HTML output you will see that both the href and target use single quotes now.

  4. I always prefer to use single quotes for HTML code strings to improve readability.

    if ($show_morelink != '') {
        $review->review_text .= '
          <a href="'.$this->get_jumplink_for_review($review,1).'" target="_blank">'.$show_morelink.'</a>';
    }
    
  5. Lots of answers; most correctly pointing out the incorrect escaping of the quotations.

    As it has not been mentioned yet sprintf() can also help with readability rather than having to concatenate strings.

    $link = $this->get_jumplink_for_review($review,1);
    $text = sprintf('<a href="%s" target="_blank">%s</a>', $link, $label);