简体   繁体   中英

WordPress get_post_meta Not Working in a Function

I have a meta box on a custom post type for width. Im trying to use get_post_meta to place some CSS in the head. Everything is working but the meta value is not passing through. Here is my function:

function mo_carousel_css(){
    global $post;
    $width = get_post_meta( $post->ID, 'mo_carousel_width', true );
    ?>
    <style type="text/css">
        .jcarousel-container-horizontal{
        width:<?php echo $width; ?>px;
        }
    </style>
    <?php
    }

I have checked the database and the meta key/value is being stored properly as mo_carousel_width and 500 respectively. I thought global $post; would be the fix but no luck.

The value is retrieved fine in the metabox in the backend by accessing $object but that doesn't seem to work either. This is code for the form that is creating the value:

    /* Display the post meta box. */
function mo_carousel_meta_box( $object, $box ) { ?>

    <?php wp_nonce_field( basename( __FILE__ ), 'mo_carousel_nonce' ); ?>
    <p>
        <span>Carousel Size</span>
        </br>
        <input type="text" name="mo-carousel-width" id="mo-carousel-width" value="<?php echo esc_attr( get_post_meta( $object->ID, 'mo_carousel_width', true ) ); ?>" size="10" />

I wrote this by studying the Shortcode API, and I think it should work but I haven't tried it.

function mo_carousel_css() {
    global $post;
    preg_match( '/' . get_shortcode_regex() . '/s', $post->post_content, $m); 
    if (is_array($m) && $m[2] == 'shortcode' ) { 
                $shortcode_args = shortcode_parse_atts( $m[3] );
        $width = get_post_meta( $shortcode_args['idatt'], 'mo_carousel_width', true );
        <style type="text/css">
            .jcarousel-container-horizontal{ width:<?php echo $width; ?>px; }
        </style>
    } 
}

Basically what it does is check if the shortcode is being used in the current post. If the shortcode is being used, retrieve the attributes from it and use the id attribute to get post meta data.

If your shortcode is [displayCustomPost id=24] then you would have to replace shortcode with displayCustomPost and idatt with id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM