Support » Plugins and Hacks » Hacks » Add Custom Field & Update it when FB like button clicked

Add Custom Field & Update it when FB like button clicked

  • Hello,

    I’ve been trying to mess around with this for a while now and I can’t seem to get things working…Here is what I would like to do:

    1. Add a custom field to a new post which is submitted to WordPress using WP user Front End (http://wordpress.org/extend/plugins/wp-user-frontend/) called facebook_likes
    2. When someone clicks “like” on the post, update the facebook_likes custom field to custom field value + 1
    3. Order the posts by the custom field, which I think I have the code for already

    I’ve attempted to use the order posts by facebook likes plugin (http://wordpress.org/extend/plugins/wp-facebook-like-posts-order/) but it doesn’t work with my theme and it has not been updated in 18months.

    Any help would be very much appreciated, so thanks in advance for any suggestions.


Viewing 13 replies - 1 through 13 (of 13 total)
  • If I understand your intent, counting actual clicks will probably eventually result in a value different than the one maintained by facebook. This could result in your site appearing broken when the facebook likes appear to be out of order.

    It sounds like the order by likes plugin uses the custom field as a sort of cache for the facebook maintained value by grabbing the latest value every time the like button widget is loaded. This sounds like a much more reliable approach. You might investigate the source code to see exactly how this is accomplished.

    If you’re having trouble getting something working, you will get more helpful responses if you illustrate exactly how something specifically isn’t working for you.

    Thank you for your response, bcworkz.

    I will attempt to have a look at the source code but I’m no programmer. To be a little more specific, this is what I am trying to get to work at the moment: I want to update the custom field in the database when a user clicks the like button. It seems that this is how to do it:

    function(response) {
    alert(‘You liked the URL: ‘ + response);

    Is there a way I can keep the user on the same page and make that “alert” part update the custom field? Doing it this way I assume is not the most scale-able solution because every like will cause a database update, and I don’t even know if this is possible because it’s javascript which is creating the event (client side) and I want to issue some php execution to the DB?


    Yes, you would use AJAX techniques. You are right in that PHP and javascript can’t directly interact, but they both “speak” http. Your server doesn’t know or care how the http request was formed, it’s received and handled, end of story. Same for the browser, it doesn’t know or care how the http response was formed, it’s received and handled. Checkout AJAX in Plugins for starters. Unfortunately, the Codex is weak on documenting this aspect, but adequate info can be found elsewhere on the ‘net. See how far you can get with that. If you get stuck, post what you have so far here and we’ll see what we can do. Good luck.

    Hi bcworkz,

    Thanks for the information. I’ve been looking at this for about 4 hours today and I’m making progress. So far I have managed to get the custom field added to each post automatically, which is good. Now I have this code on a page in my site:

    <fb:like send="true" width="450" show_faces="true"></fb:like>
    <script type="text/javascript">
        function(response) {
            $.post("fbtest.php", category: 845 );

    And this is the contents of fbtest.php:

    $vcatid = $_POST["category"];
    $meta_val = get_post_meta(845, 'fb_likes', true);
    $fbmetval = intval($meta_val);
    $fbmetval = fbmetval + 1;
    update_post_meta(845, 'fb_likes', $fbmetval);

    I’ve hard coded the post ids just to see if I can get it working first, then I’ll switch them to variables later. This doesn’t work though. I’m trying to see if it’s even being called from the Ajax call but I’m still trying to work out how to do that…

    Am I heading down the correct route?

    Thanks for your help,

    P.S. The get_post_meta call in fbtest.php doesn’t work, it errors with:

    Fatal error: Call to undefined function get_post_meta()

    But it works when I use it on an existing page. I assume it’s because I need to do some kind of include at the top of the page but I’m not sure what to include as none of the other php files in my theme have any calls like that.

    I’ve got it working now 😀

    I had to add a call to this to get it working:


    Happy with that!
    Thanks again,

    Bit stuck again. I can get it working if I hard code the values but now when passing a variable to it. I think I must be specifying it incorrectly:

    <script type="text/javascript">
        function(response) {
            $.post("http://www.my_domain.com/fbtest.php", { category: ".$vpostid.$" } );

    I’ve tried quite a few different combinations for the category part, such as:

    $.post("http://www.my_domain.com/fbtest.php", { category: $vpostid } );

    But the only one which works is when I hard code the category and have it like this:

    $.post("http://www.my_domain.com/fbtest.php", { category: "845"} );

    So I guess the question is how to I wrap my variable in double quotes.


    I’m not sure about the context your snippet comes from, it appears to be part of plain html, in which case, to insert a php value, you need to echo it from inside a php block:
    {category: <?php echo $vpostid; ?>}

    You don’t need quotes for this since it is an integer value, but for reference, the quotes are placed outside the php block to pass strings:
    {post_name: "<?php echo $vpostname; ?>"}

    Another alternative, if you were to echo out the entire html/script code from php, would be to enclose the html in double quotes and use single quotes within the html/script. Then any php variables encountered are automatically expanded with the variable’s value.
    <?php echo "{post_name: '$vpostname'}"; ?>

    If you did it the other way around, it doesn’t work because php does not expand variables inside single quotes, only double. You would be forced to concatenate the string instead.
    <?php echo '{post_name: "' . $vpostname . '"}'; ?>

    If you really need double quotes inside a double quote string, you escape it with a backslash.
    <?php echo "{post_name: \"$vpostname\"}"; ?>

    I actually dislike inline script and prefer javascript in an included file, even if it’s only 5 lines of code. As a separate file, to get it included in a WP header, we must use wp_enqueue_script(). This gives us a tag we can use to reference our script, and ensures dependencies are dealt with properly. With a tag, we can use wp_localize_script() to create a javascript object that contains arbitrary data values which will be locally available to our script.

    The result is we can reference php values using javascript variables, so our javascript is not confused with interspersed php stuff. While it’s an extra step, I like the elegance of the two languages being completely separate, not only in the script, but separate files as well.

    That last bit is probably too much information right now, but keep it in mind for the future, I think it’s an excellent approach. You’ve obviously struggled due to gaps in your knowledge, but you’ve made good progress considering, you should be pleased with yourself.


    Cheers bc, thank you for the information. I totally get the keeping the javascript code separate from the php. I imagine that it helps a lot when you have a large scale project with a lot of code to manage, then you can just reference code snippets and it will look a lot cleaner.

    I assumed that I needed the number in quotes because that’s the only way I could get it to work but I think I found another issue…I’m pretty sure that something is wrong with my fbtest.php because it won’t use the hard-coded value. I’ve looked around all last night but it still looks correct to me. Is there something obviously wrong with it:

    /** Set up WordPress environment */
    require_once( './wp-load.php' );
    require_once( './wp-admin/admin-ajax.php' );
    $vcatid = $_POST["category"];
    $meta_val = get_post_meta($vcatid, 'fb_likes', true);
    $fbmetval = intval($meta_val);
    $fbmetval = $fbmetval + 1;
    update_post_meta($vcatid, 'fb_likes', $fbmetval);

    Thanks again for all your help. I feel like I’m making progress and I’m almost there with this!


    I’ve never POSTed an AJAX request to a custom file in WP, I’m unsure how to setup the proper environment. The usual way to handle AJAX in WP is to include an “action” value in the data array for the jQuery .post() function, and submit it directly to admin-ajax.php.
    $.post("http://www.my_domain.com/wp-admin/admin-ajax.php", { category: "845", action: "update_likes" } );
    (AFAIK, you can usually pass integers as integers or strings, it gets properly typed most of the time automatically)
    With .post() done that way, the PHP handler code hooks into the action ‘wp_ajax_update_likes’ and the other data is available in the $_REQUEST array. (If the user is not logged in, the action preface used is “wp_action_nopriv_”)

    function update_likes() {
      $vcatid = $_REQUEST["category"];
      // insert the rest of the php stuff...
    add_action('wp_ajax_update_likes', 'update_likes');

    Then you don’t need a custom PHP file, the code can reside in a plugin or theme functions.php.

    Evening BC,
    Thanks for replying. I like what you are saying there about not having to have the separate php file, it’s a much more elegant way of dealing with it.

    However, I have it all working now 🙂 After 10+ hours of trying! The problem with my original code for the Ajax part was that I was using $.post. When I changed it to jquery.post it started posting through. I was so happy to spot that…

    So, I now have my final, albeit slightly hacky, way of doing it:

    1. Add custom field automatically with the post when it’s added by a user
    2. Capture the FB like button click and use Ajax to send the information to the php page which updates the custom field and adds 1 to it.
    3. Order my posts in WordPress by the number of FB likes.

    Job done! Well, one of them…On to the next one.

    Thanks again for all your help, bc, I have learned a few things from what you have said and your guidance helped me a lot.


    wow – RobReg could you please contact me pertaining to code – I’ve spent way more than ten hours trying to achieve similar results but have not been successful – i wanted to view a demo and possible speak with you on getting code and or instructions for me to implement it! thanks in advance and you might not claim to be a programmer but the code you hold is poetry to me!

    Hello @nathanssimpson,

    Haha! I know how you feel, it can take a long time to get these things working. I’ll try to help you get it working. Here are some instructions:


    1. I am using the WP-Clear theme (3.2)
    2. I wanted to order all category posts by the number of Facebook likes I have the following two plugins: Ultimate Facebook (premium plugin http://premium.wpmudev.org/project/ultimate-facebook/). I’m very sure that you can do it without this to be honest, but you’ll need some way of getting all the Facebook stuff working. If you look on the Facebook developers site and use the set-up there it should work. Or, if you get a free Facebook plugin just so that the shortcodes for it to work that should be enough. And WP User Frontend (http://wordpress.org/extend/plugins/wp-user-frontend/)
    3. On my website I allow logged in users (they can only log in with Facebook) to add posts – this is what Wp user front end does.


    Get above two plugins installed and working. In order to get the Facebook likes part working I added a custom field to every new post. Because I didn’t want to have to do it manually (because people can post any time of day or night), I modified the WP User Frontend plugin to add a new custom field when a new post was added. To do that, edit the wpuf-add-post.php file from within the plugin’s directory and add a new line just below the if ($post_id) { line, as below:

    if ( $post_id ) {
    	    //add mandatory FB likes custom field. Added by RJ
    	    add_post_meta( $post_id, 'fb_likes', '0', true );

    That will add a new custom field called fb_likes every time a post is added but ONLY through the Wp User Frontend plugin. If you add new posts manually, you should probably add it as well.

    Next, add the code for a like button to your post (single.php). I think you can probably just use the Ultimate Facebook plugin but I haven’t tested that yet. Here is the Facebook button code and the code to capture when you get a click on the like button:

    Put this at the top of single.php

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#" >
    <div id="fb-root"></div>

    Then you need to find a way of getting the post id. I used this:

    $vpostid = $post->ID; ?>

    Next, add the Ajax code, the event capture and the FB like button code:

    function(response) {
    jQuery.post("http://www.my-domain.com/fbtest.php", { category: <?php echo $vpostid; ?> } );
    <fb:like send="true" width="450" show_faces="true" font="verdana"></fb:like>

    You’ll notice in the above that there is a fbtest.php file. You will need to create that, too. Here is the code I used:

    require( './wp-load.php' );
    global $wpdb;
    $vcatid = $_POST['category'];
    $meta_val = get_post_meta($vcatid, 'fb_likes', true);
    $fbmetval = intval($meta_val);
    $fbmetval = $fbmetval + 1;
    update_post_meta($vcatid, 'fb_likes', $fbmetval);

    Finally, and this works if you want the posts to be ordered by the fb_likes custom field on the category sub-pages (not sure of the technical term for this…), add this code to index1.php:

    // Added by RJ for ordering by FB links custom field
    if (is_category()) {
    global $wp_query;
    $args = array_merge( $wp_query->query_vars, array( 'meta_key' => 'fb_likes', 'orderby' => 'meta_value' ) );
    query_posts( $args );

    You should add the above code just below this piece of existing code in index1.php:

    if (is_home() || is_page()) {
    		'post__not_in' =>  $do_not_duplicate,
    		'paged' => $paged

    Bear in mind that some of this might be specific to my theme. I am use WP-Clear by Solostream. I’ve not looked at any other themes before so I don;t know if single.php, etc are common names and layouts for the files.

    Let me know how you get on. Good luck!

Viewing 13 replies - 1 through 13 (of 13 total)
  • The topic ‘Add Custom Field & Update it when FB like button clicked’ is closed to new replies.