Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Wordpress Customizer in Javascript

I have made a customized control for the Wordpress Customizer and I would like to set my control inside a script (Instafeed.js), to change the limit number.

Following this answer this is how I did it so far

<script type="text/javascript">  
          var userFeed = new Instafeed({
            get: '',
            tagName: '',
            clientId: '',
            limit: var imglimit = <?php echo json_encode($imglimit); ?>;,
            });
            userFeed.run();
</script>

Functions

$wp_customize->add_setting(
        'imglimit',
        array(
            'default'      => '',
            'section'      => 'section',
));
$wp_customize->add_control('imglimit', array(
      'label'      => __('test'),
      'section'    => 'section',
      'settings'   => 'imglimit',
      'type'       => 'select',
      'choices'    => array(
        '5'   => '5',
        '10'  => '10',
        '20'  => '20',
      ),
));

function theme_customizer()
{
    $imglimit = get_theme_mod('imglimit');
}

Could anyone tell me where is the mistake ? I've been searching for this for a while.

like image 282
dbsso Avatar asked Oct 30 '22 12:10

dbsso


1 Answers

Well, you've got a syntax error here :)

      var userFeed = new Instafeed({
        get: '',
        tagName: '',
        clientId: '',
        limit: var imglimit = <?php echo json_encode($imglimit); ?>;,
//             ^^^^^^^^^^^^ here                      and here     ^ 
        });

So, you should change that block of code to

      var userFeed = new Instafeed({
        get: '',
        tagName: '',
        clientId: '',
        limit: <?php echo json_encode($imglimit); ?>,
      });

Actually you don't necessarily need to json encode here since it's just a number. But if that was some array or object, yes, you should've encoded that.

And in your php code you should make $imglimit global:

function theme_customizer()
{
    global $imglimit;
    $imglimit = get_theme_mod('imglimit');
} 

Or just put that into js:

      var userFeed = new Instafeed({
        get: '',
        tagName: '',
        clientId: '',
        limit: <?php echo json_encode(get_theme_mod('imglimit')); ?>,
      });
like image 58
Alexander Mikhalchenko Avatar answered Nov 12 '22 20:11

Alexander Mikhalchenko