Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

PHP syntax question

Posted on 2015-01-13
15
Medium Priority
?
112 Views
Last Modified: 2015-01-25
Hi - I've got a simple plugin code for Wordpress to permanently delete the first image located in all posts as I've migrated to a new theme and we're now using the Featured Image. I'm aware of the filter trick to hide the first image, but I'd rather get my content healthy and strip out the unneeded, manually entered images at the front of posts.

The code I found below is almost there, but it deletes all content in the post, rather than just that first image. Is there a minor tweak to get this to do what I was expecting? I have backups and can run trial and error of course, but I think this is close:

<?php
/**
 * Plugin Name: First Image Remover
 * Description: Remove the first image from the post content
 * Plugin URI:  http://wordpress.stackexchange.com/a/142494/26350 
 * Version:     0.0.1
 */

/**
 * Create the 'First Image Remover' admin menu
 */

function wpse_142494_create_menu()
{
    // Create new top-level menu:
    add_menu_page( 
        'First Image Remover', 
        'First Image Remover', 
        'manage_options', 
        'wpse_142494_settings_page', 
        'wpse_142494_settings_page'
    );
}

add_action('admin_menu', 'wpse_142494_create_menu');

/**
 * Create the 'Image Replacer' settings pge
 */
function wpse_142494_settings_page()
{ 
?>
    <div class="wrap">
        <h2>First Image Remover</h2>
        <p>Remove the first image of each post in the selected loop.</p>


        <h3>Help:</h3>
        <p>Avialable GET parameters: 
        <pre>
wpse_ppp - Posts Per Page (int), 
wpse_offset - Offset (int),
wpse_update - Update mode (boolean) 

Update Example for 5 posts with offset 10:

/wp-admin/admin.php?page=wpse_142494_settings_page&wpse_offset=10&wpse_ppp=5&wpse_update=yes
        </pre>
        <h3>Loop:</h3>
        <?php wpse_142494_loop(); ?>
    </div>
<?php
}

/**
 * Fetch posts based on user input
 */
function wpse_142494_loop()
{
    // Only site admin can update posts:
    if( ! current_user_can( 'manage_options' ) ) return;

    // Get user input:
    $params = filter_input_array( INPUT_GET, array( 
        'wpse_offset'  => FILTER_SANITIZE_NUMBER_INT,
        'wpse_ppp'     => FILTER_SANITIZE_NUMBER_INT, 
        'wpse_update'  => FILTER_VALIDATE_BOOLEAN, 
    ) );

    // Fetch posts to update:   
    $posts = get_posts( array( 
        'post_type'      => 'post', 
        'posts_per_page' => ( ! empty( $params['wpse_ppp'] ) )    ? $params['wpse_ppp']    : 10 , 
        'offset'         => ( ! empty( $params['wpse_offset'] ) ) ? $params['wpse_offset'] : 0, 
    ) );

    // Loop through posts:
    $li = '';
    foreach( $posts as $post ):

        if( $params['wpse_update'] ):           
            // Update each post with your reg-ex content filter:
            $pid = wp_update_post( array( 
                'ID'           => $post->ID,
               // 'post_content' => preg_replace( "/<img[^>]+\>/i", "", $post->post_content, 1 )
				'post_content' => preg_replace( "<a href[^>]+\><img[^>]+\></a>", "", $content, 1)
            ) );

            // Show the update process:
            $li .= sprintf( '<li>%d - <strong>%s</strong> - was %s updated</li>', 
                $post->ID, 
                $post->post_title,
                ( 0 < $pid ) ? '' : 'NOT' 
            );
        else:
            // Show the post list that will be updated
            $li .= sprintf( '<li>%d - <strong>%s</strong> - will be updated</li>', 
                $post->ID,
                $post->post_title
            );
        endif;

    endforeach;

    // Output:
    printf( '<strong>Settings:</strong> Posts: %d - Offset: %d - Update: %s <ul>%s</ul>', 
        $params['wpse_ppp'], 
        $params['wpse_offset'], 
        $params['wpse_update'] ? 'ON' : 'OFF', 
        $li 
    );
}

Open in new window


Any suggestions?

Thank you

Bill
0
Comment
Question by:billium99
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 6
15 Comments
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40548505
If this:
               // 'post_content' => preg_replace( "/<img[^>]+\>/i", "", $post->post_content, 1 )

Open in new window

was the original code, then I think the line:
				'post_content' => preg_replace( "<a href[^>]+\><img[^>]+\></a>", "", $content, 1)

Open in new window

should be:
				'post_content' => preg_replace( "<a href[^>]+\><img[^>]+\></a>", "", $post->post_content, 1)

Open in new window


If that doesn't work, can you please copy and paste the HTML of a post for us to see, so the pattern can be checked?
0
 
LVL 1

Author Comment

by:billium99
ID: 40549949
Sorry for the delay - trying this soon...
0
 
LVL 1

Author Comment

by:billium99
ID: 40551714
OK Hi Guys,

Thanks for the time!

I just modified the line, imported the posts again, and tried to run the page again. It's still deleting everything within the post. Here is one sample article that is fairly typical. This is the first paragraph:

<p>By Dr. Royal Lee</p> <p><a href="the-lee-foundation-for-nutritional-research"><img class=" alignleft size-full wp-image-24" src="http://coloradoweb5.com/wp-content/uploads/2014/10/images_article_images_lfnr-watermark-small.jpg" border="0" style="float: left; margin-left: 5px; margin-right: 5px;" width="50" height="53" /></a><strong>Summary</strong>: There's no point talking about—or restricting—the consumption of table salt without considering the potassium level of an individual. So says Dr. Lee in this discussion of the critical relationship between the minerals sodium and potassium in the body. "The present custom of restricting salt for patients with cardiovascular disease seems to be an ill-advised substitute for balancing up their potassium-sodium intake. A deficiency of potassium may be a primary cause of the very condition in which sodium is being restricted, and [more dietary] potassium [may] be the real remedy needed." 1951.</p>
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 1

Author Comment

by:billium99
ID: 40551716
Er - first 2 paragraphs rather...
0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40553118
Ha, silly me. We're missing the pattern delimiters. You should have triggered a PHP error from that, but not seen it? Try this:

				'post_content' => preg_replace( "#<a href[^>]+><img[^>]+></a>#", "", $post->post_content, 1)

Open in new window

0
 
LVL 1

Author Comment

by:billium99
ID: 40553844
Thanks Terry - I think this is working. One question:

If I see that some posts had that first image, but someone stripped out the HREF, could I run another sweep like this?

'post_content' => preg_replace( "#<img[^>]+>#", "", $post->post_content, 1)

Open in new window


Would that work? And now will this find the "second" image (now the new first image because of the previous pass) and wipe that one instead?

Would it be better to set the criteria of the one and only pass to check for both conditions? What would that syntax be?

Thank you

Bill
0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40554605
Strip out the first image, with the a tag optional, like this:
				'post_content' => preg_replace( "#(<a href[^>]+>)?<img[^>]+>(</a>)?#", "", $post->post_content, 1)

Open in new window

0
 
LVL 1

Author Comment

by:billium99
ID: 40556234
Thank you Terry - I keep adding to the question, but it's still not removing the images (at least it's no longer deleting the post content entirely).

I'm not sure I understand what the offset is supposed to do in the context of this code. The URL parameter that I've been trying is:

/wp-admin/admin.php?page=wpse_142494_settings_page&wpse_offset=0&wpse_ppp=700&wpse_update=yes

The original forum post with this code had a side comment that only said, "Offset is the amount offset you want" but I suspect it could be related to my plight?

Any ideas?

Thanks again

Bill
0
 
LVL 35

Accepted Solution

by:
Terry Woods earned 2000 total points
ID: 40556820
The offset is passed to get_posts:
    // Fetch posts to update:   
    $posts = get_posts( array( 
        'post_type'      => 'post', 
        'posts_per_page' => ( ! empty( $params['wpse_ppp'] ) )    ? $params['wpse_ppp']    : 10 , 
        'offset'         => ( ! empty( $params['wpse_offset'] ) ) ? $params['wpse_offset'] : 0, 
    ) );

Open in new window


to help with debugging, perhaps try adding this line before the preg_replace:
die($post->post_content);

Open in new window

that should exit the program and output the first post it tries to remove an image from.
0
 
LVL 1

Author Comment

by:billium99
ID: 40561060
So you are saying the offset value should equal the number of posts?
0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40561169
No, I think it's probably intended to be the number of characters to ignore at the start of each post, should that be necessary.
0
 
LVL 1

Author Comment

by:billium99
ID: 40564447
Sorry Terry I'm troubleshooting two different issues in two different systems at the moment. So I'm not sure of the syntax for adding your suggested debugging code:

die($post->post_content);
                        'post_content' => preg_replace( "#(<a href[^>]+>)?<img[^>]+>(</a>)?#", "", $post->post_content, 1)
            ) );

That has syntax errors. Even if I remove the semicolon on the die line.

Where exactly was that supposed to be inserted?

Thanks

Bill
0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40565916
Try putting the line with die before the line:
            $pid = wp_update_post( array( 

Open in new window

0
 
LVL 1

Author Comment

by:billium99
ID: 40569620
Hmm - as soon as I did that, it found the first post with an image. So I marked out the die, and boom - it finally worked as expected!

Thanks for the help Terry!

Bill
0
 
LVL 1

Author Closing Comment

by:billium99
ID: 40569622
Thanks again!
0

Featured Post

Looking for a new Web Host?

Lunarpages' assortment of hosting products and solutions ensure a perfect fit for anyone looking to get their vision or products to market. Our award winning customer support and 30-day money back guarantee show the pride we take in being the industry's premier MSP.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The purpose of this video is to demonstrate how to Test the speed of a WordPress Website. Site Speed is an important metric of a site’s health. Slow site speed can result in viewers leaving your site quickly and not seeing your content. This…
The purpose of this video is to demonstrate how to set up an RSS Feed on a WordPress Website. This will be demonstrated using a Windows 8 PC. Feedburner will be used for this demonstration. Go to your WordPress login page. This will look like the…
Suggested Courses

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question