How to connect to the WordPress core posts scripts?

I try to connect Javascript and WordPress blog posts.

As I understand each social network uses system where URL is shared for the particular post.

An example:

1. https://x.com/intent/post?url=
2. https://www.facebook.com/sharer/sharer.php?u=
3. https://www.linkedin.com/shareArticle?mini=true&url=

How to connect a script to the PHP posts?

<div class="a2a_kit a2a_kit_size_32 a2a_default_style">
    <a class="a2a_button_facebook"></a>
    <a class="a2a_button_mastodon"></a>
    <a class="a2a_dd" href="https://www.addtoany.com/share"></a>
</div>

<span id="events_demo"></span>

<script>
// A custom "onReady" handler for AddToAny
function my_addtoany_onready() {
    events_demo.innerHTML = 'AddToAny is ready!';
}

// A custom "onShare" handler for AddToAny
function my_addtoany_onshare(data) {
    events_demo.innerHTML = 'Shared &quot;<a href="'
        + data.url
        + '">'
        + data.title
        + '</a>&quot; to '
        + data.service
        + '!';
}

// Setup AddToAny "onReady" and "onShare" callback functions
var a2a_config = a2a_config || {};
a2a_config.callbacks = a2a_config.callbacks || [];
a2a_config.callbacks.push({
    ready: my_addtoany_onready,
    share: my_addtoany_onshare,
});
</script>

Hi, for me it’s a bit unclear what you’re trying to achieve here. On a WordPress site, AddToAny normally doesn’t require any custom JavaScript, you just install and activate the plugin and it automatically generates the correct share URLs for each post.

From your example, it seems you are trying to do something more custom which involves manually passing the post URL/title back into the script.

Could you clarify what the end goal is? For example, are you trying to track shares, or customise the shared URL?

I try to make sharing more custom. How to do passing the post URL/title back into the script without breaking in WordPress functionality and Codex?

On a standard WordPress post, there’s nothing to “expose”. The post URL and title already exist in the rendered page, and JavaScript can read them directly.

The URL is already available via window.location.href and The title is already available via document.title, or document.querySelector('h1').textContent. Is there any reason you cannot use those?

Thank you for the message!

I will test a demo.

You do not connect JavaScript directly to the core scripts. WordPress already gives you the post data in PHP.

Inside the post loop, you can get the current post URL with get_permalink() and pass it into your JavaScript or directly into the share links.

In PHP it is usually done like this. You echo the permalink into the URL parameter for each network. That is how most share buttons work.

WordPress handles which post is being viewed. Your script just uses the current post URL, nothing more complex than that.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.