I’m looking to create a function that will add a link to a div (or replace the div with the div and a link – in simple; I’m trying to create a plugin that will turn the header image into a clickable link without a code edit).
Maybe I’m going about this wrong but the path I chose was str_replace. I was hoping something like this would work:
$content = str_replace('<div class="header-object">', '<div class="header-object"><a href=â<?php bloginfo(âsiteurlâ); ?>â></a>, '<div class="header-object">';
The image is called through the “header-object” css class. So that’s the entire div minus the end call. This code doesn’t even come close to working (even as a header.php code edit). Any thoughts?
Why not do this with jQuery? It would be a very simple, here’s a sample, provided you have a means to get the blog’s URL into the jQuery code:
This will wrap
<a>
tags around an image inside the.header-object
class.To implement this into your code, it is run as a script like so:
You can really put that anywhere but it’s recommended you put it in the
<head>
tag. If you do put it in the head tag (and not enqueue it with wp_enqueue_script) you could use<?php echo home_url(); ?>
in place of#blog url here#
.So this is what it would look like in your PHP file inside the
<head>
tag. You will need to include jQuery as well so I added an extra<script>
tag for that, it is absolutely needed when running any jQuery (if your theme doesn’t already have jQuery loaded that is!):The above is an extremely basic example to help you understand, what you need to do is use what WP already has available for you. Using
wp_enqueue_scripts
in yourfunctions.php
file. Assuming you are using a basic theme that does not already enqueue jQuery AND no plugins that enqueue jQuery, the following code would work.Take the jQuery code that wraps the image in
<a>
tags and put it in a file calledanything.js
in your theme’s folder, in this example it will bethemes/yourtheme/js/wrapheaderimg.js
– note that<?php echo home_url(); ?>
will not work here because it’s not a PHP file.Second open (or create one if it doesn’t exist)
functions.php
in your theme’s directory, and the following code should automatically add the scripts you need inside the<head>
tag:Now remember that
echo home_url();
won’t work in that .js file, so if you are just using this for yourself, assuming the URL will always be the same, you could hard-code it in, otherwise there’s another way of doing it but I don’t know if it is best practices. Here it goes:When you enqueue your scripts in your
functions.php
file, the file extension doesn’t have to be.js
, you can make it.php
so long as your JS file has a.php
extension and the appropriate header at the very top of the file:And then back in
functions.php
you could do something like this to pass the blog’s URL to the Javascript file:And now back in your custom PHP Javascript file, you can access that variable with this, essentially using
echo $_REQUEST['url'];
:Hope this helps.