Solved

PHP syntax question

Posted on 2015-01-13
15
99 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
  • 9
  • 6
15 Comments
 
LVL 35

Expert Comment

by:Terry Woods
Comment Utility
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
Comment Utility
Sorry for the delay - trying this soon...
0
 
LVL 1

Author Comment

by:billium99
Comment Utility
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
 
LVL 1

Author Comment

by:billium99
Comment Utility
Er - first 2 paragraphs rather...
0
 
LVL 35

Expert Comment

by:Terry Woods
Comment Utility
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
Comment Utility
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
Comment Utility
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 1

Author Comment

by:billium99
Comment Utility
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 500 total points
Comment Utility
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
Comment Utility
So you are saying the offset value should equal the number of posts?
0
 
LVL 35

Expert Comment

by:Terry Woods
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks again!
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now