• Resolved TheD4h101

    (@thed4h101)


    I want to make it so Screenshot posts are formatted easily by automatically editing the image widths to fit onto my page.

    This is what I have so far:

    $contentWidth = 'width=\"600px\"';
    $quarterWidth = 'width=\"25%\"';
    $halfWidth = 'width=\"50%\"';
    $fullWidth = 'width=\"100%\"';
    
    $screenContent = the_content();
    $screenContent = preg_replace("/width=\"(.*?)\"/is", $contentWidth, $screenContent);
    echo $screenContent;

    However the preg_replace must not be working as the image in the post is still huge. Any suggestions?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    The preg_replace is working, but you’re inserting bad html. Inside of single quoted strings, you do not escape double quotes. The backslashes are getting into your html, resulting in invalid width attributes, which are ignored. Check you output source and you will see.

    Thread Starter TheD4h101

    (@thed4h101)

    Yeah I know that, what you see is just one of the methods I’ve tried.. Literally done everything I can do. I’ve even done:

    $screenContent .= 'width="1920px"';
    
    $screenContent = preg_replace("/width="(.*?)"/is", $contentWidth, $screenContent);

    And that works fine for that part..

    The fact is that “the_content()” isn’t a function, it’s a hook. So even putting $screenContent = the_content(); will call the hook and cause it to echo out. I need to find a way to preg_replace it for only certain category posts.

    Moderator bcworkz

    (@bcworkz)

    Heh, I totally missed the_content() blunder and the fact it echoes out. You want to use get_the_content() in order to get a returned value that you can play with before echoing out.

    Now that it’s not yet echoed out, you can determine the categories of the current post and conditionally apply the modification. Assuming this is inside the ‘Loop’, the post object is available as $post, so you can get category IDs with wp_get_post_categories( $post->ID ).

    Thread Starter TheD4h101

    (@thed4h101)

    That worked perfectly. All I had to do was replace the_content with get_the_content() and the code worked fine.

    To summarise, I placed the following code in the PHP file of the Category I wanted it to work on. (I.e. Post Category, Review Category, Screenshots Category or Videos Category)

    $contentWidth = 'width="600px"';
    
    $screenContent = get_the_content();
    $screenContent = preg_replace("/width=\"(.*?)\"/is", $contentWidth, $screenContent);
    echo $screenContent;
    Thread Starter TheD4h101

    (@thed4h101)

    Check previous post for answer.

    Just marking the topic as closed ??

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Edit Image Widths in the_content()’ is closed to new replies.