• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 116
  • Last Modified:

PHP syntax question

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
billium99
Asked:
billium99
  • 9
  • 6
1 Solution
 
Terry WoodsIT GuruCommented:
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
 
billium99Author Commented:
Sorry for the delay - trying this soon...
0
 
billium99Author Commented:
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 Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
billium99Author Commented:
Er - first 2 paragraphs rather...
0
 
Terry WoodsIT GuruCommented:
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
 
billium99Author Commented:
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
 
Terry WoodsIT GuruCommented:
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
 
billium99Author Commented:
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
 
Terry WoodsIT GuruCommented:
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
 
billium99Author Commented:
So you are saying the offset value should equal the number of posts?
0
 
Terry WoodsIT GuruCommented:
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
 
billium99Author Commented:
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
 
Terry WoodsIT GuruCommented:
Try putting the line with die before the line:
            $pid = wp_update_post( array( 

Open in new window

0
 
billium99Author Commented:
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
 
billium99Author Commented:
Thanks again!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 9
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now