0

I'm working on my portfolio and I need to set a custom background color and image for each post in my 'Portfolio' category. I used custom data to store the color and the image url, and i'm trying to print the new css on my page.

I can't use true inline css (like style="") because of a JS script I made which uses it already and makes conflict.

So I tried use wp_add_inline_style :

<?php // File "content-thumbnail.php" used for each post. So, we're in the Loop here. ?>

<div class="post-circle">
    <?php lethal_post_circle_background(get_the_ID()); ?>
    <div class="post-circle-summary">
        <p class="post-title"><?php the_title(); ?></p>
        <p class="post-categories"><?php lethal_post_categories_portfolio(); ?></p>
    </div>
    <div class="post-circle-content">
    </div>
</div>

And then the script to add the style :

<?php
function lethal_post_circle_background($id){
    $custombgcolor = get_post_meta( $id, 'bgcolor', true );
    $custombgimage = get_post_meta( $id, 'bgimage', true );
    if($custombgcolor | $custombgimage){
        $css = '.post-'.$id.' .post-circle{
        background:';
        if($custombgcolor) $css .= $custombgcolor . ' ';
        if($custombgimage) $css .= 'url("' . $custombgimage . '")';
        $css.= ';}';

        wp_add_inline_style('lethal-style', $css);
    }

}

The problem is that the genereted style isn't in the generated html file, but the wp_add_inline_style() function returned true (so I think everything is ok). I don't have any error or Notice messages.

Do you know what is the problem ?

Thanks !

1

You need to hook wp_add_inline_style to wp_enqueue_scripts. Check the codex example. Something like (not tested):

function lethal_post_circle_background(){
    global $post;
    $id = $post->ID;
    $custombgcolor = get_post_meta( $id, 'bgcolor', true );
    $custombgimage = get_post_meta( $id, 'bgimage', true );
    if($custombgcolor | $custombgimage){
        $css = '.post-'.$id.' .post-circle{
        background:';
        if($custombgcolor) $css .= $custombgcolor . ' ';
        if($custombgimage) $css .= 'url("' . $custombgimage . '")';
        $css.= ';}';

        wp_add_inline_style('lethal-style', $css);
    }

}
add_action( 'wp_enqueue_scripts', 'lethal_post_circle_background' );
  • But if I've 5 posts on my page, I need to call this function 5 times, with another ID each time, right ? Can I hook this function once per post ? – Thaledric Feb 26 '16 at 21:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.