append wordpress post title with jquery

2019-09-16 01:30发布

问题:

i want add the title <?php the_title(); ?> after my selector by jquery

('a img').after('<span>the title here</span>'); 

回答1:

PHP code is interpreted on the server, jQuery code in the browser (long after the PHP interpreter has finished). They can't really see each other.

What you can do is put the value of the_title() in some element on the page and then use jQuery to locate it and add it:

var title = $('#the_title').text();
$('a img').after('<span>' + title + '</span>'); 

[EDIT] If you have several titles, then you must map them to the images somehow. There are many possible ways to do that:

  • You can send the name of the image to the PHP server, have it look up the title and send that back. Look up $().json().

  • You can put all the titles in some piece of HTML that you make invisible by wrapping it in <div style="display: none;">. In your jQuery, you can then map images to titles.



回答2:

What Aaron said.

But maybe using a custom data attribute so (so it validates in HTML5).

In your PHP:

<img data-title="<?php the_title(); ?>" src="..." />

In javascript (jQuery):

$('a img').each(function(){
   var title = $(this).attr("data-title");
   $(this).after('<span>' + title + '</span>');
});

Untested but that's the idea. Tested.