0

I have a script on a buddypress set up which shows a user on the 'members area' if they have a notification, it just prints "You have new notifications (22)" or "You do not have any notifications".

Typical set up, I am a little lost on how to correctly print a link that is not going to change..

Currently the code for when they have a notification is;

if ( $instance['show_count_in_title'] ) {
    printf( "<span class='notification-count-in-title'>(%d)</span>", $count );
}

However when I add in the link to the text, it breaks, I have tried within the span and outside, but always in the (".. I am not totally clued up on PHP so maybe I am wrong to use links in this way? But I guess more so I am confused to why

When I do this;

if ( $instance['show_count_in_title'] ) {
    printf( "<a href="me/notifications"><span class='notification-count-in-title'>(%d)</span></a>", $count );
}

I get the following error:

Parse error: syntax error, unexpected 'http' (T_STRING) in /homepages/2/d676463482/htdocs/dc/wp-content/plugins/buddypress-notifications-widget/core/class-bp-notification-widget.php on line 59

I presume I am entering the a href incorrectly for PHP but I have struggle to figure out what it should be.

Daniel Hobbs
  • 119
  • 2
  • 14

3 Answers3

2

You need to escape your backslashes:

printf( "<a href=\"me/notifications\"><span class='notification-count-in-title'>(%d)</span></a>", $count );

Or continue using single slashes:

printf( "<a href='me/notifications'><span class='notification-count-in-title'>(%d)</span></a>", $count );

Furthermore, I would strongly suggest using single quotes, and using double quotes inside. (More info on this here):

printf( '<a href="me/notifications"><span class="notification-count-in-title">(%d)</span></a>', $count );

Because you are not including variables within the string (You're passing them in via printf), there's no reason to have PHP try to parse the string to look for variables.

  • Thanks this worked perfectly. Also super helpful to know the different ways and the preferred way to do. Thanks loads, really has helped clear this up for me. – Daniel Hobbs Aug 01 '18 at 18:19
1

Use single quotes or escape the inner double-quotes:

printf( '<a href="me/notifications"><span class="notification-count-in-title">(%d)</span></a>', $count );

... or:

printf( "<a href=\"me/notifications\"><span class='notification-count-in-title'>(%d)</span></a>", $count );
Roman Hocke
  • 4,137
  • 1
  • 20
  • 34
1

You need to either escape

  printf( "<a href=\"me/notifications\"><span class=\"notification-count-in-title\">(%d)</span></a>", $count );

or use ''

  printf( '<a href="me/notifications"><span class="notification-count-in-title">(%d)</span></a>', $count );
Robert
  • 19,800
  • 5
  • 55
  • 85