Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Media Command Laravel Package

wp-cli/media-command

WP-CLI media commands for WordPress: import files as attachments, regenerate thumbnails, replace attachment files, list registered image sizes, and fix image orientation. Useful for bulk media maintenance and automation from the command line.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require wp-cli/media-command
    

    Or via WP-CLI:

    wp package install wp-cli/media-command
    
  2. First Use Case: List all registered image sizes to understand your WordPress environment:

    wp media image-size
    
  3. Quick Import: Import a local image and attach it to a post:

    wp media import ~/path/to/image.jpg --post_id=123 --title="My Image"
    

Implementation Patterns

Common Workflows

Bulk Media Operations

  • Regenerate thumbnails for all images (e.g., after theme/plugin updates):
    wp media regenerate --yes
    
  • Prune unused thumbnails (cleanup):
    wp media prune --remove-abandoned --yes
    

Post-Specific Media Handling

  • Set imported media as featured image:
    wp media import ~/image.jpg --post_id=456 --featured_image
    
  • Replace an existing attachment (e.g., update a product image):
    wp media replace 789 ~/new-image.jpg
    

Automated Pipelines

  • Import from URLs in bulk (e.g., for a gallery):
    wp media import http://example.com/image1.jpg http://example.com/image2.jpg --post_id=789
    
  • Chain commands (e.g., import + set as featured):
    ATTACHMENT_ID=$(wp media import ~/image.jpg --porcelain)
    wp post meta add 789 _thumbnail_id $ATTACHMENT_ID
    

Debugging & Maintenance

  • Fix orientation issues (e.g., after bulk uploads):
    wp media fix-orientation --dry-run  # Preview
    wp media fix-orientation           # Apply
    
  • List image sizes for debugging:
    wp media image-size
    

Integration Tips

Laravel + WP-CLI

  1. Run WP-CLI from Laravel: Use Artisan to execute WP-CLI commands via shell:

    // app/Console/Commands/RegenerateThumbnails.php
    public function handle() {
        $exitCode = Artisan::call('wp media regenerate --yes');
        if ($exitCode !== 0) {
            $this->error('Thumbnail regeneration failed.');
        }
    }
    
  2. Dynamic Post IDs: Fetch post IDs from Laravel and pass them to wp media import:

    $posts = Post::where('status', 'publish')->get();
    foreach ($posts as $post) {
        Artisan::call('wp media import', [
            'path/to/image.jpg',
            '--post_id=' . $post->id,
            '--title=' . $post->title,
        ]);
    }
    
  3. Event-Driven Workflows: Trigger WP-CLI commands after Laravel events (e.g., postUpdated):

    event(new PostUpdated($post));
    // In listener:
    Artisan::queue('wp media regenerate ' . $post->id);
    

Custom Scripts

  • Bash Script for Bulk Imports:

    #!/bin/bash
    find ~/uploads -name "*.jpg" | while read file; do
        wp media import "$file" --post_id=123 --skip-duplicates
    done
    
  • Laravel Task Scheduler: Schedule thumbnail regeneration nightly:

    $schedule->command('wp media regenerate --yes')->daily();
    

Gotchas and Tips

Pitfalls

  1. Permission Issues:

    • Ensure the WordPress user (e.g., www-data) has write access to:
      • wp-content/uploads/
      • Thumbnail directories (e.g., wp-content/uploads/2023/05/).
    • Fix: Run WP-CLI with sudo or adjust permissions:
      chown -R www-data:www-data wp-content/uploads/
      
  2. Memory Limits:

    • Regenerating large thumbnails may hit PHP memory limits.
    • Fix: Increase memory_limit in wp-cli.yml or php.ini:
      memory_limit = 512M
      
  3. Duplicate Handling:

    • --skip-duplicates may not work as expected if filenames differ but content is identical.
    • Fix: Use wp media import --porcelain + custom logic to check hashes.
  4. URL vs. Local Paths:

    • URLs require --skip-copy (files are downloaded temporarily).
    • Local paths may fail if the path is relative to the WP-CLI execution context.
    • Fix: Use absolute paths or cd into the correct directory first.
  5. Multisite Conflicts:

    • Commands may target the wrong site if not prefixed with --url.
    • Fix: Always specify the site URL:
      wp --url=https://site.com media regenerate
      

Debugging Tips

  1. Dry Runs:

    • Use --dry-run or --yes to test commands safely:
      wp media fix-orientation --dry-run
      wp media prune --yes
      
  2. Verbose Output:

    • Enable debug mode for troubleshooting:
      WP_CLI_DEBUG=1 wp media import ~/image.jpg
      
  3. Log File Analysis:

    • Check wp-content/debug.log for errors after failed operations.
  4. Image Size Mismatches:

    • If thumbnails appear broken, verify registered sizes:
      wp media image-size
      
    • Re-register missing sizes via functions.php:
      add_image_size('custom-size', 800, 600);
      

Extension Points

  1. Custom Image Sizes:

    • Extend the package by adding new image sizes via WordPress filters:
      add_filter('intermediate_image_sizes_advanced', function($sizes) {
          $sizes['my-custom-size'] = ['width' => 1200, 'height' => 800, 'crop' => true];
          return $sizes;
      });
      
  2. Pre/Post-Import Hooks:

    • Use WordPress hooks to modify behavior:
      add_action('add_attachment', function($attachment_id) {
          // Custom logic after import
      });
      
  3. WP-CLI Aliases:

    • Create shortcuts in ~/.wp-cli/config.yml:
      aliases:
          regen-thumbs: 'media regenerate --yes'
          clean-thumbs: 'media prune --remove-abandoned --yes'
      
  4. Testing:

    • Mock HTTP requests for URLs in Behat tests:
      Given that HTTP requests to "http://example.com" will respond with:
        """
        <binary-image-data>
        """
      

Pro Tips

  1. Batch Processing:

    • Use xargs for large datasets:
      seq 1 1000 | xargs -P 4 wp media regenerate
      
  2. Post Meta Updates:

    • Update _wp_attachment_metadata after replacements:
      wp media replace 123 ~/new.jpg --skip-delete
      wp post meta update 123 _wp_attachment_metadata '{"width": 2000, "height": 1500}'
      
  3. CI/CD Integration:

    • Add to deployment scripts:
      # After theme/plugin updates
      wp media regenerate --yes
      
  4. Performance:

    • Regenerate thumbnails in parallel (if supported by your server):
      parallel -j 4 wp media regenerate ::: $(seq 1 1000)
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony