# Managing Languages

> **Complete guide** to language configuration, management, and optimization

---

## Table of Contents

1. [Language Overview](#language-overview)
2. [Adding Languages](#adding-languages)
3. [Configuring Languages](#configuring-languages)
4. [URL Structures](#url-structures)
5. [Language Detection](#language-detection)
6. [RTL Language Support](#rtl-language-support)
7. [Language Priorities](#language-priorities)
8. [Removing Languages](#removing-languages)
9. [Import/Export](#importexport)
10. [Best Practices](#best-practices)

---

## Language Overview

### What is a Language?

In Multilingual Press Zone, a language represents:

- **Language Code**: ISO 639-1 (e.g., `en`, `es`, `fr`)
- **Locale**: Full locale identifier (e.g., `en_US`, `es_ES`, `fr_FR`)
- **Display Name**: English name (e.g., "Spanish")
- **Native Name**: Native language name (e.g., "Español")
- **URL Configuration**: How URLs are structured
- **Text Direction**: LTR or RTL
- **Status**: Active or inactive

### Default Language

Every site must have exactly one default language:

- ✅ First language shown to new visitors
- ✅ Fallback when translation doesn't exist
- ✅ Original content language
- ✅ Cannot be deleted (must switch default first)
- ✅ Usually matches site's primary language

---

## Adding Languages

### Method 1: Quick Add (Recommended)

Use pre-configured language templates:

1. **Navigate to Languages**
   - Go to **Settings → Multilingual Press Zone → Languages**

2. **Click Quick Add**
   - Click **Quick Add** button (top right)
   - Popular languages appear in dropdown

3. **Select Language**
   - Choose from list (e.g., Spanish - Español)
   - All fields auto-populated with correct values
   - Click **Add Language**

**Available in Quick Add:**
- Spanish (Español) - es_ES
- French (Français) - fr_FR
- German (Deutsch) - de_DE
- Italian (Italiano) - it_IT
- Portuguese (Português) - pt_PT
- Portuguese Brazil (Português do Brasil) - pt_BR
- Chinese Simplified (简体中文) - zh_CN
- Chinese Traditional (繁體中文) - zh_TW
- Japanese (日本語) - ja
- Korean (한국어) - ko
- Arabic (العربية) - ar
- Hebrew (עברית) - he
- Russian (Русский) - ru
- And 50+ more...

### Method 2: Manual Add

For custom configurations:

1. **Click Add Language**
   - Languages page → **Add New Language** button

2. **Fill in Details**

   **Required Fields:**
   ```
   Language Code: es (ISO 639-1, 2 letters)
   Locale: es_ES (language_COUNTRY format)
   Name: Spanish (English name)
   Native Name: Español (native name)
   ```

   **Optional Fields:**
   ```
   Flag: 🇪🇸 (emoji or code)
   Sort Order: 10 (display order)
   ```

3. **Configure Settings**
   - URL Structure (subdirectory/subdomain/parameter)
   - Text Direction (LTR/RTL)
   - Status (Active/Inactive)

4. **Save Language**
   - Click **Save Language**
   - Language appears in list

### Method 3: Bulk Import

For adding many languages at once:

1. **Download Template**
   - Languages page → **Import/Export** → **Download CSV Template**

2. **Fill in Languages**
   ```csv
   code,locale,name,native_name,flag,url_structure,text_direction,is_active
   es,es_ES,Spanish,Español,🇪🇸,subdirectory,ltr,1
   fr,fr_FR,French,Français,🇫🇷,subdirectory,ltr,1
   de,de_DE,German,Deutsch,🇩🇪,subdirectory,ltr,1
   ```

3. **Import CSV**
   - Languages page → **Import/Export** → **Import Languages**
   - Upload CSV file
   - Click **Import**

4. **Verify Import**
   - Check all languages added correctly
   - Fix any errors reported

---

## Configuring Languages

### Language Settings

Each language has individual settings:

#### Basic Information

**Language Code** (`code`)
- 2-letter ISO 639-1 code
- Examples: `en`, `es`, `fr`, `de`, `ja`, `zh`, `ar`
- Used in URLs (if subdirectory structure)
- Cannot be changed after creation

**Locale** (`locale`)
- Full locale identifier: `language_COUNTRY`
- Examples: `en_US`, `en_GB`, `es_ES`, `es_MX`
- Used for date/time formatting
- Used for number formatting
- WordPress core translations matching

**Name** (`name`)
- English name of language
- Used in admin interface
- Examples: "Spanish", "French", "German"

**Native Name** (`native_name`)
- Name in the language itself
- Used in language switcher
- Examples: "Español", "Français", "Deutsch"

**Flag** (`flag_code`)
- Emoji flag: 🇪🇸, 🇫🇷, 🇩🇪
- Or text code: "ES", "FR", "DE"
- Optional but recommended for better UX

#### URL Configuration

**URL Structure** (`url_structure`)

Three options:

1. **Subdirectory** (Recommended)
   ```
   example.com/        (default language)
   example.com/es/     (Spanish)
   example.com/fr/     (French)
   ```
   ✅ Best for SEO
   ✅ Easy setup
   ✅ Works with all hosts

2. **Subdomain**
   ```
   example.com         (default language)
   es.example.com      (Spanish)
   fr.example.com      (French)
   ```
   ✅ Separate domains for languages
   ⚠️ Requires DNS configuration
   ⚠️ Separate SSL certificates

3. **Parameter**
   ```
   example.com/        (default language)
   example.com/?lang=es (Spanish)
   example.com/?lang=fr (French)
   ```
   ⚠️ Not ideal for SEO
   ⚠️ Used as fallback only

**Custom Slug**
- Override default URL slug
- Example: Use `/spanish/` instead of `/es/`
- Useful for branded URLs

#### Display Settings

**Sort Order** (`sort_order`)
- Controls order in language switcher
- Lower numbers appear first
- Default: 0 (language creation order)

**Status** (`is_active`)
- **Active**: Visible on frontend, translatable
- **Inactive**: Hidden, useful for:
  - Languages in preparation
  - Seasonal languages
  - A/B testing

**Default Language** (`is_default`)
- One language must be default
- To change default:
  1. Edit new default language
  2. Check "Set as default"
  3. Save (automatically removes default from old language)

#### Text Direction

**LTR** (Left to Right)
- Most languages
- English, Spanish, French, German, Chinese, Japanese, etc.
- Default setting

**RTL** (Right to Left)
- Arabic, Hebrew, Persian, Urdu
- Automatically:
  - Reverses text alignment
  - Flips UI elements
  - Mirrors layouts

---

## URL Structures

### Subdirectory Structure (Recommended)

**Configuration:**

1. Go to **Settings → Multilingual Press Zone → Settings → URL Structure**
2. Select **Subdirectory**
3. Configure options:

**Options:**

```php
// Remove language prefix from default language
✅ Enable this option

Result:
English (default): example.com/about/
Spanish: example.com/es/about/
French: example.com/fr/about/

// Keep language prefix for all languages
❌ Disable this option

Result:
English: example.com/en/about/
Spanish: example.com/es/about/
French: example.com/fr/about/
```

**Custom Slugs:**
- English: (empty - no prefix)
- Spanish: `spanish` (uses /spanish/ instead of /es/)
- French: `francais` (uses /francais/ instead of /fr/)

**Permalink Settings:**

Ensure WordPress permalinks are enabled:
- Go to **Settings → Permalinks**
- Select any option except "Plain"
- Recommended: **Post name** (`/%postname%/`)

**Server Configuration:**

Apache (automatically works with .htaccess)

Nginx (add to config):
```nginx
location ~ ^/(es|fr|de)/ {
    try_files $uri $uri/ /index.php?$args;
}
```

### Subdomain Structure

**Setup Required:**

1. **DNS Configuration**
   - Add A records for each language subdomain:
   ```
   es.example.com → Your server IP
   fr.example.com → Your server IP
   de.example.com → Your server IP
   ```

2. **SSL Certificates**
   - Wildcard SSL: `*.example.com`
   - Or individual certificates per subdomain

3. **Server Configuration**

   Apache (VirtualHost):
   ```apache
   <VirtualHost *:443>
       ServerName example.com
       ServerAlias *.example.com
       DocumentRoot /var/www/html
   </VirtualHost>
   ```

   Nginx:
   ```nginx
   server {
       listen 443 ssl;
       server_name example.com *.example.com;
       root /var/www/html;
   }
   ```

4. **WordPress Configuration**
   ```php
   // wp-config.php
   define('DOMAIN_CURRENT_SITE', 'example.com');
   define('COOKIE_DOMAIN', '.example.com'); // Note the leading dot
   ```

**Advantages:**
- Completely separate domains
- Can use different CDNs per language
- Better for very large sites

**Disadvantages:**
- More complex setup
- Higher hosting costs
- Requires wildcard SSL

### Parameter Structure

**When to Use:**
- Temporary solution
- Testing before full deployment
- Fallback when subdomains not available

**Configuration:**

1. Select **Parameter** in URL Structure settings
2. Choose parameter name: `lang` (default) or custom

**Result:**
```
example.com/about/              (default language)
example.com/about/?lang=es      (Spanish)
example.com/about/?lang=fr      (French)
```

**SEO Considerations:**
- Google may treat as duplicate content
- Use `<link rel="alternate" hreflang="x">` tags
- Not recommended for production sites

---

## Language Detection

### Auto-Detection Methods

**1. Browser Language**

Detects from `Accept-Language` HTTP header:

```
Accept-Language: es-ES,es;q=0.9,en;q=0.8
```

**How It Works:**
1. User visits site for first time
2. Plugin reads browser language preference
3. Redirects to matching language
4. If no match, shows default language

**Configuration:**
```
Settings → General → Language Detection
✅ Enable browser language detection
Priority: 1 (highest)
```

**2. Cookie**

Remembers user's language choice:

**How It Works:**
1. User selects language via switcher
2. Cookie saved: `mpz_language=es`
3. Next visit shows remembered language

**Configuration:**
```
Cookie name: mpz_language
Expiration: 1 year
Domain: .example.com (for subdomains)
```

**3. User Profile**

For logged-in users:

**How It Works:**
1. User sets preferred language in profile
2. Language saved to user meta
3. Overrides browser and cookie detection

**Configuration:**
```
Users → Profile → Preferred Language
Shows dropdown of available languages
```

**4. GeoIP**

Detects from IP address location:

**Requires:**
- GeoIP database (MaxMind)
- PHP GeoIP extension

**How It Works:**
1. Gets user's IP address
2. Looks up country
3. Matches to language

**Configuration:**
```bash
# Install GeoIP
sudo apt-get install php-geoip geoip-database

# Enable in plugin
Settings → General → Language Detection
✅ Enable GeoIP detection
Priority: 2 (after cookie)
```

### Detection Priority

Configure detection order:

```
1. User Profile (logged-in users)
2. Cookie (returning visitors)
3. Browser Language (new visitors)
4. GeoIP (if available)
5. Default Language (fallback)
```

**Recommendation:**
- Priority 1: Cookie
- Priority 2: User Profile
- Priority 3: Browser Language
- Priority 4: GeoIP
- Fallback: Default Language

### First-Visit Behavior

**Options:**

1. **Auto-redirect** (recommended)
   - Automatically redirect to detected language
   - Show notification: "You've been redirected to Spanish"
   - Allow switching back

2. **Show popup**
   - Display language selector popup
   - User chooses language
   - Choice saved in cookie

3. **Show banner**
   - "This site is available in: [languages]"
   - User can click to switch
   - Less intrusive than popup

**Configuration:**
```
Settings → General → First Visit Behavior
○ Auto-redirect with notification
○ Show language selection popup
○ Show language selection banner
○ No action (show default language)
```

---

## RTL Language Support

### Enabling RTL

**Automatic Detection:**

Plugin automatically enables RTL for:
- Arabic (ar)
- Hebrew (he)
- Persian/Farsi (fa)
- Urdu (ur)
- Yiddish (yi)

**Manual Configuration:**

For other RTL languages:

1. Edit language
2. Set **Text Direction** to **RTL**
3. Save language

### What Changes in RTL Mode

**Automatic Changes:**

1. **Text Alignment**
   ```css
   body.lang-ar {
       direction: rtl;
       text-align: right;
   }
   ```

2. **Layout Mirroring**
   - Menus flip to right side
   - Sidebar moves to left
   - Floats reversed
   - Padding/margins mirrored

3. **UI Elements**
   - Icons flip horizontally
   - Arrows point opposite direction
   - Scrollbars move to left

**Theme Support:**

Most modern themes support RTL automatically. If not:

1. Check theme supports RTL:
   ```php
   // functions.php
   add_theme_support('rtl');
   ```

2. Create RTL stylesheet:
   ```
   style-rtl.css (auto-loaded in RTL languages)
   ```

3. Test thoroughly:
   - Navigation
   - Forms
   - Tables
   - Custom layouts

### RTL Best Practices

**CSS Guidelines:**

```css
/* Use logical properties instead of directional */
/* ❌ Avoid: */
margin-left: 20px;
padding-right: 10px;
float: left;

/* ✅ Use: */
margin-inline-start: 20px;
padding-inline-end: 10px;
float: inline-start;
```

**Image Guidelines:**

- Avoid directional arrows in images
- Use CSS for directional UI elements
- Mirror images with directional meaning
- Don't mirror faces or text in images

**Testing Checklist:**

- [ ] Navigation menu aligned correctly
- [ ] Sidebar on correct side
- [ ] Forms display properly
- [ ] Tables columns reversed
- [ ] Buttons aligned correctly
- [ ] Icons flipped appropriately
- [ ] Text alignment correct
- [ ] Mobile responsive works

---

## Language Priorities

### Sort Order

Control display order in language switcher:

**Default Order:**
```
1. English (sort_order: 0)
2. Spanish (sort_order: 0)
3. French (sort_order: 0)
```
(Ordered by creation date)

**Custom Order:**
```
1. English (sort_order: 1)
2. Spanish (sort_order: 2)
3. French (sort_order: 3)
4. German (sort_order: 4)
```

**How to Set:**

1. Languages page → Edit language
2. Set **Sort Order** field
3. Lower numbers appear first
4. Save

**Bulk Reorder:**

1. Languages page → **Bulk Actions** → **Reorder**
2. Drag languages into desired order
3. Click **Save Order**

### Visibility Control

**Active vs Inactive:**

**Active Languages:**
- ✅ Visible in language switcher
- ✅ Can create translations
- ✅ Appear in content lists
- ✅ Accessible on frontend

**Inactive Languages:**
- ❌ Hidden from language switcher
- ✅ Can still edit existing translations
- ❌ Hidden from new translation options
- ❌ Not accessible on frontend

**Use Cases for Inactive:**
- Preparing new language before launch
- Temporarily disabling language
- Seasonal languages
- Testing translations

**How to Deactivate:**

1. Edit language
2. Uncheck **Active** checkbox
3. Save

Or bulk action:
1. Select languages
2. **Bulk Actions** → **Deactivate**
3. Click **Apply**

---

## Removing Languages

### Before Removing

**⚠️ Warning:** Removing a language:
- Deletes all translations in that language
- Breaks language switcher references
- Removes translation relationships
- Cannot be undone

**Backup First:**
1. Export translations (Settings → Import/Export)
2. Download database backup
3. Document language configuration

### Safe Removal Process

**Step 1: Deactivate**
1. Edit language
2. Uncheck **Active**
3. Save
4. Test site thoroughly

**Step 2: Export Data**
```bash
# Via WP-CLI
wp mpz export-language es --output=spanish-translations.json

# Or via admin
Settings → Import/Export → Export Language
```

**Step 3: Remove Translations**

Optional: Delete translations first
1. Translations page
2. Filter by language
3. Bulk select all
4. Delete

**Step 4: Delete Language**
1. Languages page
2. Hover over language
3. Click **Delete**
4. Confirm deletion

### Alternative: Archive Language

Instead of deleting:

1. **Deactivate** language
2. Export all translations
3. Keep language configuration
4. Can reactivate later

**Benefits:**
- No data loss
- Easy to reactivate
- Preserves translation relationships

---

## Import/Export

### Export Languages

**Export All Languages:**

1. Settings → Import/Export
2. Click **Export All Languages**
3. Download JSON file

**Export Single Language:**

1. Languages page
2. Hover over language
3. Click **Export**
4. Download JSON file

**What's Included:**
- Language configuration
- All translations
- Translation metadata
- Statistics

### Import Languages

**Import Configuration:**

1. Settings → Import/Export
2. Click **Import Languages**
3. Upload JSON file
4. Review import preview
5. Click **Import**

**Import Options:**
- **Skip existing**: Don't overwrite existing languages
- **Update existing**: Overwrite with imported data
- **Create only**: Only add new languages

**Validation:**
- Checks for duplicate language codes
- Validates locale formats
- Ensures data integrity
- Reports errors before importing

### Bulk Operations

**CSV Export:**

Languages → Export → Download CSV

```csv
code,locale,name,native_name,flag,url_structure,text_direction,is_active,sort_order
en,en_US,English,English,🇺🇸,subdirectory,ltr,1,1
es,es_ES,Spanish,Español,🇪🇸,subdirectory,ltr,1,2
fr,fr_FR,French,Français,🇫🇷,subdirectory,ltr,1,3
```

**CSV Import:**

1. Edit CSV file (Excel, Google Sheets)
2. Languages → Import → Upload CSV
3. Map columns if needed
4. Import

---

## Best Practices

### Language Selection

**Choose Wisely:**
- Add languages where you have demand
- Don't add "just in case" languages
- Each language needs maintenance
- Consider translation costs

**Market Research:**
- Check Google Analytics for visitor locations
- Survey your audience
- Research competitor languages
- Test with small language set first

### Naming Conventions

**Consistency:**
- Use standard locale codes (`en_US` not `en-us`)
- Use official language names in English
- Use native script for native names
- Use official emoji flags

**Examples:**
```
✅ Good:
Code: zh
Locale: zh_CN
Name: Chinese Simplified
Native: 简体中文

❌ Bad:
Code: chinese
Locale: zh-cn
Name: Chinese
Native: Chinese
```

### URL Structure Strategy

**For Most Sites:**
```
Use: Subdirectories
Example: example.com/es/
Reason: Best SEO, easy setup, universal support
```

**For Enterprise:**
```
Use: Subdomains
Example: es.example.com
Reason: Separate indexing, CDN flexibility, brand separation
```

**For Testing:**
```
Use: Parameters
Example: example.com/?lang=es
Reason: Quick setup, no server config needed
```

### Performance Optimization

**Cache Configuration:**
```
Object Cache: Redis/Memcached
Page Cache: Separate cache per language
CDN: Language-aware caching
```

**Database:**
```
Index: All language queries indexed
Optimization: Monthly table optimization
Cleanup: Remove orphaned translations
```

**Monitoring:**
```
Track: Cache hit ratio per language
Monitor: Query performance per language
Alert: Performance degradation
```

### Maintenance Schedule

**Weekly:**
- [ ] Check translation status
- [ ] Review new content needing translation
- [ ] Monitor performance metrics

**Monthly:**
- [ ] Optimize database
- [ ] Export backups
- [ ] Review inactive languages
- [ ] Check for orphaned translations

**Quarterly:**
- [ ] Audit language usage
- [ ] Review and update documentation
- [ ] Plan new language additions
- [ ] Security audit

---

## Troubleshooting

### Language Not Showing in Switcher

**Possible Causes:**
1. Language is inactive
2. No translations exist
3. Cache not cleared
4. Template issue

**Solutions:**
```bash
# Check language status
wp db query "SELECT * FROM wp_mpz_languages WHERE code='es'"

# Activate language
wp mpz activate-language es

# Clear cache
wp cache flush
wp mpz clear-cache

# Verify switcher code
wp eval "mpz_language_switcher();"
```

### URLs Not Working

**Symptoms:**
- 404 errors on language URLs
- Redirects not working
- Language detection fails

**Solutions:**
```bash
# Flush rewrite rules
wp rewrite flush

# Check .htaccess
cat .htaccess | grep mpz

# Test URL structure
curl -I https://example.com/es/

# Verify language URLs
wp mpz list-languages --format=table
```

### RTL Not Applied

**Check:**
1. Language text direction setting
2. Theme RTL support
3. Cache cleared
4. Body class present

**Debug:**
```javascript
// Check body class in browser console
document.body.classList.contains('rtl');

// Check direction
getComputedStyle(document.body).direction === 'rtl';
```

---

## Next Steps

- ✅ [Translating Content](translating-content.md) - Create translations
- ✅ [Workflow System](workflow-system.md) - Team collaboration
- ✅ [Performance Tuning](../guides/performance-tuning.md) - Optimize speed

---

**Master language management for a successful multilingual site!**
