Wordpress get_post_meta not working inside a .php

2019-08-04 03:34发布

问题:

I want to tie in jquery functions with post meta options, so I have created a PHP file with jQuery code inside the PHP tags.

      <?php
      echo "
           function dynamicAdjust() {
             jQuery('#main-home').css('margin-top', jQuery(window).height());       
           }
       ";
       ?>

Maybe there is a better way to create dynamic PHP (let me know if there is) with post meta options, but the jQuery here works fine, I enqueued in in my functions.php as a javascript file, and the jQuery funciton works fine.

The issue and the whole point of having the jQuery inside a PHP file is for users to turn options on/off so for example when I wrap the code up there in an if statement like so.

       <?php
         if(get_post_meta($post->ID, '_moon_full_static_area', true) == 'on'); {
            echo "
               function dynamicAdjust() {
               jQuery('#main-home').css('margin-top', jQuery(window).height());     
               }
             ";
            }
        ?>

This gives me this error Fatal error: Call to undefined function get_post_meta() in my dir..

Ok so according to the message its obvious that it does not see get_post_meta as a function, I know anything that has post_meta enabled is connected to the database, Im just not sure what else I need to do other than enqueue the script?? Any ideas?

PS.. Best Practice for Including JS (with PHP) in WordPress Functions file I came across this, is this what I am looking for?

回答1:

The standard way to pass PHP values to your Javascript files is through wp_localize_script .
See also in WordPress Answers.

add_action( 'wp_head', 'localize_script_so_17497763' );

function localize_script_so_17497763() 
{ 
    // Maybe check for `is_single()` or other Conditional Tag

    // Check post meta 
    global $post;
    $get_meta = get_post_meta( $post->ID, '_moon_full_static_area', true );
    $meta_value = ( $get_meta == 'on' ) ? 'on' : 'off';

    // Build localization array to be passed
    $localize_array = array(
            'moon'    => $meta_value,
            'post_id' => $post->ID,
            'title'   => $post->post_title,
    );

    wp_enqueue_script( 'my-file', plugin_dir_path( __FILE__ ).'my-file.js', array('jquery') );
    wp_localize_script( 'my-file', 'wplocal', $localize_array );
}

And then, in my-file.js:

console.log( wplocal.moon );
console.log( wplocal.post_id );
console.log( wplocal.title );

See: What is the JavaScript equivalent of var_dump or print_r in PHP?