Forums

Looking for an image function (24 posts)

  1. iamchel
    Member
    Posted 2 years ago #

    Im just curious if anyone could help me out..I'm looking for a function that will tell me if there is an image included in a post. What I plan on doing is altering the default layout with a conditional statement to load one layout if the post contains an image and another if it doesn't.

    Does such a function exist? Or is there a better way to do this ie a plugin or something? Thanks.

  2. tugbucket
    Member
    Posted 2 years ago #

    If you're not opposed to using jQuery for this you can use:

    $(function () {
    if ( $('.post img').length > 0 ) {
    $('head').append('<link rel="stylesheet" href="alternate.css" type="text/css" />');
    }
    });

    That will check to see if there is an image tag inside <div class="post"> (the default class from WP). If there is, write an additional CSS file into the head. In that file you can simply overwrite exiting CSS to restyle the page.

  3. iamchel
    Member
    Posted 2 years ago #

    well what I was thinking of doing was using fields..but I cant wrap my head around how it would work. The only change in layout Id have it do is add an extra column in the html.

  4. tugbucket
    Member
    Posted 2 years ago #

    Not sure what you mean by 'using fields'. Do you have an example somewhere?

    http://www.wprecipes.com/wordpress-tip-detect-if-a-post-has-at-least-one-image

    That is a php way to check if an image exists in a post. I guess it all depends on what you want the final outcome to be.

    You say you want to add another column. Is that going to be in the 'post' or on the page itsself like

    post | sidebar <- no image
    post | column | sidebar <- with image

    If that's what you're looking for something like:

    <?php
    $content = $post->post_content;
    $searchimages = '~<img [^>]* />~';
    
    /*Run preg_match_all to grab all the images and save the results in $pics*/
    
    preg_match_all( $searchimages, $content, $pics );
    
    // Check to see if we have at least 1 image
    $iNumberOfPics = count($pics[0]);
    
    if ( $iNumberOfPics > 0 ) {
         $columnize = "true";
    } else {
         $columnize = "false";
    
    ?>

    Then outside the loop where you want the column:

    <?php
    if ($columnize == "true"){
        echo "your column stuff here";
    }
    ?>
  5. iamchel
    Member
    Posted 2 years ago #

    the field comment was just an idea..I have no idea how or if it could work. My situation is that Im trying to work with a fairly abnormal design that requires two different ways of displaying the posts depending on if the user attached an image or not. The way I have it set up (in html and css) is two div's - nested in a larger one with overflow: auto so its scrollable, the left div is for an image, while the right one is for the posts text/content. You can think of the left div as a sort of just a picture to represent the post (for instance here: http://www.wprecipes.com/wordpress-tip-get-all-custom-fields-from-a-page-or-a-post the image with all the different colored wp logos). The right side is going to hold the actual post (the whole thing = excluding that intro picture). The problem is that there is no guarantee that the user will post that picture so I need to alter the layout to just one column that spans the width of the original two. While I like the idea of it detecting if there is an image attached, there is still a chance that they will post a picture within the actual content of the post so it wont really work to well...that's why I was thinking about using a field.

    I know this probably quite confusing but I plan on posting a screenshot of what I mean when I get out of class...

  6. iamchel
    Member
    Posted 2 years ago #

    here we go..this is what I'm working with.

    First with the display picture
    http://img40.imageshack.us/i/postwith.gif/

    and without
    http://img14.imageshack.us/i/postwithout.gif/

  7. tugbucket
    Member
    Posted 2 years ago #

    Do you already have the system where your users can upload that 'avatar' image? Does your system give that image a specific class or id?

  8. iamchel
    Member
    Posted 2 years ago #

    No I figured it was possible to just pull the images out of the entries content (the attached files) since Im guessing it stores them in an array..or something lol. I'm open to suggestions as this is driving me nuts :p

    I have the logic set out I'm just not sure if its possible or how to do it..basically it goes as follows:

    -check to see if post contains any images
    -if images found
    -loop through images and test to see if any meet the minimum width requirement to qualify as the intro/avatar pic
    (note* it has to have a certain minimum width or else the design is going to look terrible, since Im using fixed widths and the two columns are split vertically with a background image)
    -if match is found apply 2 column layout (place the image in the left column, rest of the content in the right etc)
    -else display a single column layout

    I really dislike how it works logically and Id love to have an option where the user can just specify if they want to add an avatar image or not when creating the entry..but that's just how I thought it might be possible.

  9. tugbucket
    Member
    Posted 2 years ago #

    Okay try this. Build your posts with both columns. In your CSS define the widths with the left column being 0px and the right as whatever the full width is.

    When your user uploads an image they can state the alt text for the image. Using jQuery you can then see if that image exists. If it does, you can then load an additional CSS to then make the columns readjust to the 2 column sizes.

    $(document).ready(function() {
    $('.post img').each(function(index){
    if ($(this).attr('alt') == 'avatar') {
    $(this).addClass('avatar');
    }
    })
    if ( $('.avatar').length > 0 ) {
    $('body').css({'background' : '#eed'}); // just for testing
    $('head').append('<link rel="stylesheet" href="alternate.css" type="text/css" />');
    }
    });

    This will look at all the images in the div.post. If an image exists with the alt of avatar, it will add the class of avatar to it. Then it checks to see if the class avatar exists. If it does, it appends the head with the new CSS.

    So in the new CSS you need to rewrite the widths of the columns and then position the avatar image absolutely up into the first column.

    Workable?

  10. iamchel
    Member
    Posted 2 years ago #

    ok Im trying to get this into my existing site now..where do I put this exactly? In header.php?

    Also once it does get the image how can I grab that particular one and make it display on the left column? Thanks for helping..and for the patience :p

  11. iamchel
    Member
    Posted 2 years ago #

    sorry that was a kind of dumb question..found that its javascript so I put it in between the head tags but its not doing anything.

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">       
    
    $(document).ready(function() {
    $('.post img').each(function(index){
    if ($(this).attr('alt') == 'avatar') {
    $(this).addClass('avatar');
    }
    })
    if ( $('.avatar').length > 0 ) {
    $('body').css({'background' : '#eed'}); // just for testing
    $('head').append('<link rel="stylesheet" href="alternate.css" type="text/css" />');
    }
    });
    
    </script>

    so what did I do wrong? lol

  12. tugbucket
    Member
    Posted 2 years ago #

    Are you sure it's not doing anything?

    If you have Firebug and the Web developer toolbar for Firefox, you can "view generated source" and look to see if the alternate.css is being appended to the head.

    Would you have a test link somewhere. It's a guessing game on this side without one.

    Remember that there are no styles or anything applied to the class avatar. Unless you actually have a CSS file named 'alternate' with rules in it for the .avatar, nothing will happen.

  13. iamchel
    Member
    Posted 2 years ago #

    when I view the source there isnt any extra stylesheet being appended.

    I am however getting this from firebug

    $ is not defined
    wordpress?paged=2()wordpress?paged=2 (line 14)
    [Break on this error] $(document).ready(function() {\n

    sorry I don't have any working example to link to..I'm doing this all on my machine.

  14. tugbucket
    Member
    Posted 2 years ago #

    sounds like the path to jQuery isn't correct.

    <script type="text/javascript" src="jquery.js"></script>

    try using an absolute path to the file like

    <script type="text/javascript" src="http://yoursite.com/jquery.js"></script>

    and see how that goes

  15. iamchel
    Member
    Posted 2 years ago #

    Alright absolute paths worked (well I had jquery.js in the wrong directory) but its still not adding the stylesheet. It is however, changing the body's bg to #eed

    *edit

    I changed the code to the following (the stylesheet's url)

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">       
    
    $(document).ready(function() {
    $('.post img').each(function(index){
    if ($(this).attr('alt') == 'avatar') {
    $(this).addClass('avatar');
    }
    })
    if ( $('.avatar').length > 0 ) {
    $('body').css({'background' : '#eed'}); // just for testing
    $('head').append('<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/alternate.css" type="text/css" />');
    }
    });
    
    </script>

    and now its including the alternate stlyesheet on every page regardless if an image with the alt attribute of avatar is present.

    Im not familiar with jquery at all so perhaps Im not understanding something..does the code above look for a specific image with the alt of avatar in a particular div? If so where is that div being specified? Thanks.

  16. tugbucket
    Member
    Posted 2 years ago #

    I think it could be trying to add PHP with JS.

    Let em try to exaplain the cade ad offer a suggestion:

    thie starts the function
    $(document).ready(function() {

    This looks for all images inside a element with a class of post, if any of the found images have the alt of avatar it adds a class of avatar to it as well

    $('.post img').each(function(index){
    if ($(this).attr('alt') == 'avatar') {
    $(this).addClass('avatar');
    }
    })

    This part then checks to see if any elemnt on the page with the class of avatar exists, then write the CSS. Remove the line above the append line. It was there just to test. Thats why the background is changing colors.

    if ( $('.avatar').length > 0 ) {
    $('body').css({'background' : '#eed'}); // just for testing
    $('head').append('<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/alternate.css" type="text/css" />');
    }
    });

    Dont wirte this:

    href="<?php bloginfo('template_directory'); ?>/alternate.css"

    Try this:

    href="http://the_full_path_to_your_CSS/alternate.css"

    I'm testing locally and it appears to work fine.

    If that doesn't work, will you post the entire head.php here (ill assume you're including all this in the head.php file). That way i can see what you are using and i can test locally as well.

  17. iamchel
    Member
    Posted 2 years ago #

    <?php
    /**
     * @package WordPress
     * @subpackage Default_Theme
     */
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>
    
    <head profile="http://gmpg.org/xfn/11">
    <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
    
    <title><?php wp_title('&laquo;', true, 'right'); ?> <?php bloginfo('name'); ?></title>
    
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">       
    
    $(document).ready(function() {
    $('.post img').each(function(index){
    if ($(this).attr('alt') == 'avatar') {
    $(this).addClass('avatar');
    }
    })
    if ( $('.avatar').length > 0 ) {
    $('head').append('<link rel="stylesheet" href="./wp-content/themes/unveiled/alternate.css" type="text/css" />');
    }
    });
    
    </script>
    
    <link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/mastersheet.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
    <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
    
    <style type="text/css" media="screen">
    
    <?php
    // Checks to see whether it needs a sidebar or not
    if ( empty($withcomments) && !is_single() ) {
    ?>
    	#page { background: url("<?php bloginfo('stylesheet_directory'); ?>/./wp-content/themes/unveiled/images/kubrickbg-<?php bloginfo('text_direction'); ?>.jpg") repeat-y top; border: none; }
    <?php } else { // No sidebar ?>
    	#page { background: url("<?php bloginfo('stylesheet_directory'); ?>/./wp-content/themes/unveiled/images/kubrickbgwide.jpg") repeat-y top; border: none; }
    <?php } ?>
    
    </style>
    
    <?php if ( is_singular() ) wp_enqueue_script( 'comment-reply' ); ?>
    
    <?php wp_head(); ?>
    </head>
    <body <?php body_class(); ?>>
    
    <div id="content">

    That is my head..its heavily modified (I admit, its pretty sloppy) to fit my needs.

    If I understood correctly

    $('.post img').each(function(index){

    .post is the class of the container? If so would it be safe to say that its alright to change it to what Im using on my end?

    I should note that it is loading the alternate stylesheet but its not working conditionally from what I can see..its just loading it for every page.

  18. iamchel
    Member
    Posted 2 years ago #

    Oddly enough I just noticed that the alternate stylesheet is being applied to the entire page.

    I have this code below and its adding the border to everything including the gravatar's I have in the sidebar...

    .avatar
    {
        border: 4px solid #000;
    }

    EDIT* heh I spoke to soon...the gravatars have the class avatar by default from this plugin lol

    EDIT2* I removed the gravatars from the sidebar and its working perfectly now. I guess the code just looks for anything named avatar and not necessarily and alt of avatar?

    Now I just need to find out how to get the image to the other div :p

    This is the code generated by the gravatar plugin Im using in case you want to inspect it some more.

    <img class="avatar avatar-42" height="42" width="42" src="http://www.gravatar.com/avatar/52e0fd687705f1f3ccbc97175953f14a?s=42&d=identicon&r=pg" alt=""/>
  19. tugbucket
    Member
    Posted 2 years ago #

    Cool, I'm glad you found that the other plugin was using the same class name before I tried to figure it out.

    So don't touch the Gravatar plugin. Instead change all the instances of 'avatar' in the script with something else. In the code below I changed it to 'pic2col', hopefully that won't conflict with anything else.

    I guess the code just looks for anything named avatar and not necessarily and alt of avatar?

    The second part of the script was looking for anything with the class 'avatar' so changing that to something super specific will work fine.

    One thing I would do is move the script below all the existing CSS links in your head tag. That way it will over write the existing when the script fires.

    Here's an example of how it can work:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title></title>
    
    <style type="text/css">
    .post {
    width: 600px;
    border: 1px solid #000;
    position: relative;
    }
    
    .post p {
    padding: 4px 8px 18px 8px;
    margin: 0;
    }
    
    .post img {
    float: left;
    display: inline;
    margin: 4px 8px 4px 8px;
    }
    
    .post_col_r {
    width: 0px;
    float: left;
    }
    
    .post_col_l {
    width: 600px;
    background: #eee;
    }
    </style>
    
    <script src="jquery/jquery-1.2.6.js" type="text/javascript"></script>
    
      <script type="text/javascript">
    $(document).ready(function() {
    $('.post img').each(function(index){
    if ($(this).attr('alt') == 'pic2col') {
    $(this).addClass('pic2col');
    }
    })
    if ( $('.pic2col').length > 0 ) {
    $('head').append('<link rel="stylesheet" href="pic2col.css" type="text/css" />');
    }
    });
    
      </script>
    
    </head>
    <body>
    <div class="post">
    <div class="post_col_r">
    </div>
    <div class="post_col_l">
    <!-- ** this is where your loop goes ** -->
    
    <!-- below is sample output from the loop -->
    <img src="120x120.gif" alt="" />
    <p>Duis condimentum, tortor et tristique fermentum, dui eros feugiat turpis, vel elementum nibh ante ut sem. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed ipsum est, sed facilisis enim. Etiam arcu augue, scelerisque vitae fermentum eu, condimentum nec leo.</p>
    <p>Praesent malesuada, purus in dapibus pharetra, lorem nibh euismod augue, id venenatis libero lectus sit amet mauris. Integer rutrum lacus at odio malesuada ac vestibulum leo consectetur. Phasellus posuere velit a neque gravida at iaculis odio lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p>
    <img src="120x120.gif" alt="pic2col" />
    </div>
    </div>
    
    </body>
    </html>

    Notice I am using a 120px x 120px image as my test image so the CSS dimensions are based on that. Also the link to my jQuery s relative to my test environment so of course you'll need to make sure it points correctly on your side.

    By default, WP gives a class of post to the post div. If you have changed that, then change it in the script and CSS accordingly.

    So you need to 'position: relative' the .post. That way you can safely 'position: absolute' the image you want to maneuver.

    So when the script successfully fires and appends the new CSS, this is the example CSS I used:

    .post_col_r {
    width: 130px;
    float: left;
    }
    
    .post_col_l {
    width: 460px;
    background: #eee;
    margin: 0 0 0 140px;
    }
    
    .pic2col {
    position: absolute;
    top: 0;
    left: 0;
    }

    It appears to work fine. Of course you'll need to adjust for your column and image sizes and spacing and what-not.

  20. tugbucket
    Member
    Posted 2 years ago #

    Okay, the script needs to be changed. IE doesn't refire the CSS that's being appended so a different approach. We'll use jQuery to write the CSS.

    $(document).ready(function() {
    $('.post img').each(function(index){
    if ($(this).attr('alt') == 'pic2col') {
    $(this).addClass('pic2col');
    }
    })
    if ( $('.pic2col').length > 0 ) {
    // $('head').append('<link rel="stylesheet" href="pic2col.css" type="text/css">');
    $('.post_col_r').css({width: '130px', float: 'left'});
    $('.post_col_l').css({width: '460px', float: 'right', background: '#9dd'});
    $('.pic2col').css({position: 'absolute', top: '0', left: '0'});
    }
    });

    I commented out the style sheet for reference. This should also be a pretty straight forward guide to writing CSS with jQuery.

  21. iamchel
    Member
    Posted 2 years ago #

    Alright its getting closer and closer to working :)

    Only problem is that its not working in ie

    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; Creative AutoUpdate v1.40.01)
    Timestamp: Wed, 14 Oct 2009 18:01:16 UTC

    Message: Invalid argument.
    Line: 1061
    Char: 4
    Code: 0
    URI: http://localhost/wordpress/jquery.js

    Not sure what that means...

  22. tugbucket
    Member
    Posted 2 years ago #

    By "not working" what do you mean exactly?

    Are you using the updated script that does not append a CSS file to the head?

  23. iamchel
    Member
    Posted 2 years ago #

    it works in ff but in ie7 I get "error on page" on the bottom left corner of the browser and it doesn't apply any of the styles from the script.

  24. tugbucket
    Member
    Posted 2 years ago #

    well crap. how about this. Save the page out as a plain HTML page and mail it to me so I can see if anything catches my eye.

    tugbucket [at] gmail [dot] com

Topic Closed

This topic has been closed to new replies.

About this Topic