0

I have a text file with post ids and attachment ids like so:

post_id,attachment_id
post_id,attachment_id
post_id,attachment_id
post_id,attachment_id

I then try to use a function inside my functions.php file like so:

function addimg() {
$fh = @fopen( dirname( __FILE__ ) . '/addimg.txt', 'r' );

if ( $fh ) {
    while ( ( $line = fgets( $fh ) ) !== false ) {
        $ids = explode( ',', $line );
        array_walk( $ids, 'trim' );
        $postid = array_shift( $ids );
        set_post_thumbnail( $postid, $ids );
    }
}
}
add_action('wp_head', 'addimg');

But nothing happens.

I've used the same procedure to add categories to posts and it works. I've also tried to manually add a featured image to a post like so:

function thumb() {

set_post_thumbnail( 1, 1);

}
add_action('wp_head', 'thumb');

And that works.

So my knowledge is too shallow to understand why what I'm trying to do doesn't work?

  • Have you tried debugging your code? Can the file actually be openend (does the function every reach the while-loop)? Are lines actually being read? By the way, using array_walk this way generates a notice, if I remember correctly, because of the number of arguments. array_map would be suited better. – engelen Jun 10 '14 at 13:37
  • I'm afraid my skills don't go as far as debugging. Can the same operation be performed from within the functions.php without the need of an external text file? Like create some array with post_id => attachment_id and then for each pair set_post_thumbnail? – kat Jun 10 '14 at 13:53
0

As you don't have much programming experience, I'll post a ready-to-use solution here. I've looked at your code a little longer, and the problem is that after array_shift, $ids is still an array. set_post_thumbnail expects and integer, not an array. You could use $ids[0] as the second parameter, but the following is a cleaner solution, in my opinion.

function wpse149149_addimg() {
    $fh = @fopen( dirname( __FILE__ ) . '/addimg.txt', 'r' );

    if ( $fh ) {
        while ( ( $line = fgets( $fh ) ) !== false ) {
            $ids = explode( ',', $line );
            array_walk( $ids, 'trim' );
            set_post_thumbnail( $ids[0], $ids[1] );
        }
    }
}

add_action( 'wp_head', 'wpse149149_addimg' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.