Rectangle 27 4

As of WordPress 3.3, this is the best way to do it, using the proper hook:

if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
    wp_deregister_script('jquery');
    wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
    wp_enqueue_script('jquery');
}

Thanks looks great, am I correct in thinking this would go in my themes functions.php? Many thanks!

No problem. You're right, this goes in your themes function.php

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

php - Wordpress: Load only one jquery script on website - Stack Overfl...

php jquery wordpress
Rectangle 27 0

Using .ready(function($){}) avoids conflict on the existing library that you might have in your system so the dollar sign (which is for jquery) is added rather than the simple function() without the parameter to avoid conflict. In your case it is most likely the WordPress Coda-Slider that conflicts with your jquery library.

See this link here which basically in the same line as your question and the Coda specific link here.

asp.net - JQuery masterpage issue - Stack Overflow

jquery asp.net master-pages
Rectangle 27 0

You should pass page info such as query_var as "data" with your ajax function.

<?php

$catsub = get_category(get_query_var('cat'));
$cat_id = $catsub->cat_ID;
?>


<script>
    $(document).on("click", "#subscribe-btn", function (e) {
        e.preventDefault();
        $('#subscribe-btn').fadeOut(300);

        $.ajax({
          url: ajaxurl,
          data: {
                action: "subscribe_cat",
                catid: "<?php echo $cat_id;?>"
          },
          success: function(response) {
                console.log(response);
         },
         error: function() {
            alert("BOo!")
         }

         }); // end ajax call

    });
</script>

Also in your ajax function you had a condition that will always evaluate to false.

add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );    
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );

function subscribe_cat(){



    //changed here!!
    $cat_id = $_POST['catid'];

    if(!$cat_id){
        echo 'cat_id is missing';   
        exit;
    } elseif(!is_user_logged_in()) {
        echo 'Not logged in!';  
        exit;
    }   

    $userid = get_current_user_id();


    $subs = get_user_meta($userid, 'user_subscriptions', true);

    if(empty($subs))
        $subs = array();

    $subs[] = $cat_id;
    update_user_meta($userid, 'user_subscriptions', $subs); 
    echo json_encode($subs);
    exit;

}

thanks for this. Just a couple of questions... can I use $_POST['catid'] to retrieve the category id? Then in jquery, can I use php tags in a js file? the ajax I coded is in a separate file.

Ok actually I got it, the only question is still because the ajax is in a separate js file is there another method to retrieve category for ajax?

yes of course. You can set a js global window var on your page and call this in your function or check out codex.wordpress.org/Function_Reference/wp_localize_script

jquery - Wordpress AJAX not calling PHP function - Stack Overflow

php jquery ajax wordpress
Rectangle 27 0

<?php if (is_page('sea-freight')): ?>
$(".va-slice-1").click();
<?php endif; ?>

thank you. I tried this, but it throws out my page with an error message?

Can you provide this message? Or, maybe, you can post a link?

wordpress - jQuery function only on certain pages - Stack Overflow

jquery wordpress function
Rectangle 27 0

you need to encapsulate your javascript in function that executes on DOM ready event

<script type="text/javascript">                 
 $(function () {
   $("comment_switch").click(function () {
    $("comments").toggleClass("hidden");
  });
});
</script>
comment_switch

jquery - How to fix "TypeError: $ is not a function" error in WordPres...

jquery html wordpress wordpress-plugin-dev
Rectangle 27 0

For dynamic drop down you need to use ajax with wordpress

I am explain all step which help you to create dynamic drop down country with city.

Please follow below steps:
Step : 1 
At first, Create Categories: Parent and Sub category from wp admin.
Step : 2

Create a template in WordPress( I am not going in details of what are the templates of WordPress and how they process in WordPress themes) in which we will implement ajax functionality. Open a new php file and save it with any name like I saved it with implement-ajax.php
Add the following code in the newly created page.

<?php
/*
Template Name: Implement Ajax
*/
get_header();
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>

<style type="text/css">
#content{width:auto; height:400px; margin:50px;}
</style>
<div id="content">
<?php
wp_dropdown_categories('show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat');
?>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
</div>
<?php
get_footer();
?>


Step :3

Now add jquery code in template 

$(function(){
  $('#main_cat').change(function(){
  var $mainCat=$('#main_cat').val();
    // call ajax
  $("#sub_cat").empty();
     $.ajax({
    url:"bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
    type:'POST',
    data:'action=my_special_action&main_catid=' + $mainCat,
     success:function(results)
     {
    //  alert(results);
    $("#sub_cat").removeAttr("disabled");
        $("#sub_cat").append(results);
        }
       });
  }
);
});


Step:6 Now add this code in function.php 


function implement_ajax() {
if(isset($_POST['main_catid']))
            {
            $categories=  get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
              foreach ($categories as $cat) {
                $option .= '<option value="'.$cat->term_id.'">';
                $option .= $cat->cat_name;
                $option .= ' ('.$cat->category_count.')';
                $option .= '</option>';
              }

              echo '<option value="-1" selected="selected">Scegli...</option>'.$option;
            die();
            `enter code here`} // end if
}
add_action('wp_ajax_my_special_action', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_action', 'implement_ajax');//for users that are not logged in.

Step :5

Now create a new page in the dashboard and assign the template to it.

php - how can i show advanced custom fields plugin fields show in fron...

php wordpress
Rectangle 27 0

You're attempting to retrieve a POST value via PHP in Javascript. This is erroneous. To do correctly, the PHP/Server-side script returns the value in either raw form, HTML or json. This result is returned as data to jQuery's AJAX method. Notice the variable value in the code below.

function displayData(id) {
    var $j = jQuery.noConflict();
    $j.ajax({
              type:'POST',
              data:{rid:id},
              url: "http://www.mywebsite.com/?page_id=123",
              success: function(value) {
                //do something with 'value'
                alert(value);
                console.log('The result is ' + value);

              }
            });
    }

yes u r right, but the "value" displayed in that way is the "html code" of the current page.

You need to recognize that the request being sent to the page is an being made by javascript [send something like ajax=true], and when this is the case, then send only your response [Raw, HTML or json]. This is how AJAX works, the response is the result of the page you are requesting.

javascript - POST with Jquery to a php function in wordpress retrieves...

php javascript jquery wordpress
Rectangle 27 0

It seems like you have to load the script using wp_enque_script. You can find the documentation for this function and for loading scripts in WordPress in general at the codex page for wp_enque_script. Furthermore, I found an article on Using jQuery with WordPress that provides sample code for the loading of the script and then the use of it.

The jQuery library included with Wordpress loads in "no conflict" mode.

So to be able to use the $() function as usual, you have to do

jQuery(document).ready(function($) {
    // $() will work as an alias for jQuery() inside of this function
});

For an example of what that looks like, look at step 2 of the Themocracy article linked above.

I'm pretty sure you'll be fine with these resources, hope they help.

Hi there, have investigated this, cheers, one extra problem was that i was calling jquery from the goolge cdn not the wordpress built in version which starts in NoConflict mode. used wp_enqueue_script('jquery'); to call this and it finally works! Cheers.

jquery and wordpress - Stack Overflow

jquery wordpress-theming
Rectangle 27 0

Based on your comments its sounds like some of the script's dependencies are missing. That is, the script assumes certain variables are defined when it runs, and they're not. jQuery needs to be present first, and then (at a minimum) the jQuery UI library you are using. So you need to make sure your script is only added to the page after those scripts.

You do this in PHP, with wp_enqueue_script(). This function handles the addition of your js file to the page, either in the header or (by default) the footer. One of the arguments for this function is an array of dependencies, so here you would pass 'jquery', 'jquery-ui', and 'jquery-ui-slider'. (These are the 'handles' by which WordPress registers each of those scripts -- there's a list of scripts that WP knows about on the page linked above.) As long as you specify all the dependencies correctly, the error you're currently getting should go away.

javascript - jQuery Script in WordPress - Stack Overflow

javascript jquery wordpress
Rectangle 27 0

Okay I've fixed it. I'm not entirely sure how, but it's done! As I had yet to replace the given code in the index.php of the theme I am using, I continued to do so while I waited for a response on this question. Magically, once the rest of my page code was loaded, the hover function worked completely.

I can only assume that this was either a collapsing issue that the .group class hadn't resolved without the remaining page code, or possibly a clash of z-index items.

Apologies for not providing more information, but it could potentially take quite some time to track down the specific cause of the issue. My advice from this would be to fill in all the html and css before worrying about getting the JS working!

wordpress - jQuery hover mouseleave function triggers when hovering ov...

jquery wordpress submenu jquery-hover
Rectangle 27 0

Why don't you simply load everything on the loop (a new foreach for subpages inside the pages' foreach loop) and then use your jQuery function (modified) to toggle the subpages on click?

Good plan. Could you provide an example for the OP to improve your answer? What you have written is more of a 'comment'.

Wordpress & Jquery: How to call a wordpress function with jquery on cl...

jquery wordpress
Rectangle 27 0

If I understand correctly, you are trying to use jQuery to do a HTTP POST request back to your WordPress app when some event happens in the browser. This is a technique known as AJAX (Asynchronous Javascript and XML). Javascript in your browser communicates with a server without refreshing the page and can do more logic you want (in Javascript/jQuery) based on the response from the server. The server can response with more than just XML these days (JSON is pretty popular).

AJAX in WordPress Plugins: Response using jQuery. You can do this in a theme instead of a plugin. This is probably what you are looking for.

Not quite... The js file loaded in the header needs to do the ajax call to a PHP function in a plugin, which will then return a value.

I promise that is what you are looking for. You cannot call PHP functions using Javascript directly. You have to pass data through requests and responses instead.

HOORAY! I don't know why Wordpress Codex explains everything in such a complicated way but I looked around, based on what you said, and found this beautifully simple example and then, when I got an 'ajaxurl undefined' error, applied this and it's all working! BOOM! Thank you :)

Create and access custom PHP function from jQuery post in Wordpress - ...

php jquery wordpress
Rectangle 27 0

There are 2 variants:

  • You have not loaded jQuery library.
  • It is not available by $ function because of prototype.js or something, then try to use jQuery function instead of $.

jquery has been loaded on line 241: plumbsimple.com while line 245 should handle the jQuery conflict: window.$ = jQuery;

javascript - basic jquery slider TypeError: $ is not a function on Wor...

javascript jquery html wordpress
Rectangle 27 0

More than likely writing the replace first "$" with "jQuery" and passing the "$" to the function will make that error go away. Example below.

`jQuery(document).ready(function($) {

            $('#slider').list({
              'animation' : 'slide',
              'width' : 700,
              'height' : 300
            });

          });`

javascript - basic jquery slider TypeError: $ is not a function on Wor...

javascript jquery html wordpress
Rectangle 27 0

First of all .hide() is not clearing content its just hidden. If you want to clear your content then just use next method

$('#scheduleBox').html('')

jquery - Loading/switching DIVs by calling unique functions (on WordPr...

jquery ajax wordpress html
Rectangle 27 0

The problem with your code is that you're not "bootstraping" your wordpress so you don't have loaded properly the wordpress object and classes when you do your ajax request. A simple (but not correct) solution is to add at the beginning of your getResults.php file something like this:

require_once( "relative/path/to/your/wp-load.php" );

php - Call to a member function get_col() on a non-object jQuery Wordp...

php jquery ajax wordpress wordpress-plugin
Rectangle 27 0

The jQuery library included with Wordpress loads in "no conflict" mode. In order to use the $ function as usual, use the following: jQuery(document).ready(function($) { // $() will work as an alias for jQuery() inside of this function }); Unfortunately, doing this causes it to break altogether so I had to switch it back to function($) { I feel I'm pretty close...

javascript - Why doesn't jQuery Tablesorter Plugin work on this Wordpr...

javascript jquery wordpress tablesorter
Rectangle 27 0

The alert is popping up after the sidebar is loaded because ready() is supposed to be executed AFTER the whole page is done loading.

jQuery ready function doesnt work in wordpress - Stack Overflow

wordpress
Rectangle 27 0

You're probably missing some . class markup and the DOM ready function

jQuery(function($){ // DOM is now read and ready to be manipulated

    $(".comment_switch").click(function () {
        $(".comments").toggleClass("hidden");
    });

});

Additionally using the jQuery object (instead of directly $) and using the jQuery alias $ inside the function's argument you make sure to skip any other library that uses the same alias ($) to interfer with the jQuery library. The jQuery argument reference $ inside jQuery(function($){ allows you to reuse it securely inside that function without any outher script interfering with that alias cause from now on it's exclusively referenced to the window.jQuery Object / library (Framework).

Yes, yes :-) You were right with both issues. I didn't 100% checked the code from stackoverflow.com/a/3102240/250422 I can understand the dots being missing but could you explain why I had to use jQuery(function($)? Thank you.

@Radek Most likely because wordpress is using $.noConflict which makes $ not equal to jQuery. you could probably instead just replace $ with jQuery to make your code work, assuming it is immediately before the closing body tag. The code in this answer makes it work because it's using jQuery on the outside, then accepting the passed argument (which just so happens to be jQuery) with a name of $ which you then used inside your code.

@Radek what I did is : get window.jQuery assign as reference argument the $, that way inside the function the $ is assigned to window jQuery reference. it's a low level way that in 90% of cases is worthy the noConflict one. It prevents you from typing all over again jQuery instead of the reference $.

@Radek It is, unless $.noConflict is being used, which is very common with wordpress.

jquery - How to fix "TypeError: $ is not a function" error in WordPres...

jquery html wordpress wordpress-plugin-dev
Rectangle 27 0

The jQuery library included with Wordpress loads in "no conflict" mode. In order to use the $ function as usual, use the following: jQuery(document).ready(function($) { // $() will work as an alias for jQuery() inside of this function }); Unfortunately, doing this causes it to break altogether so I had to switch it back to function($) { I feel I'm pretty close...

javascript - Why doesn't jQuery Tablesorter Plugin work on this Wordpr...

javascript jquery wordpress tablesorter