PHP RegExp String Conversion

User
convert (J)VGL106871001867753816 to JVGL106871001867753816 in php by regexp
Assistant
To convert a string like `(J)VGL106871001867753816` to `JVGL106871001867753816` using a regular expression in PHP, you can use `preg_replace()`.

### โœ… PHP Code:

<?php
$input = '(J)VGL106871001867753816';
$output = preg_replace('/^((w))/', '$1', $input);

echo $output; // Outputs: JVGL106871001867753816

### ๐Ÿ” Explanation:
– `^((w))`:
– `^` ensures the match is at the start of the string.
– `(` and `)` match literal parentheses.
– `(w)` captures a single alphanumeric character (like `J`).
– `$1` inserts the captured letter (e.g. `J`) without the parentheses.

Let me know if the pattern varies and you need more flexible matching.

User
also what if string is already JVGL106871001867753816
Assistant
If the string is already in the correct format (e.g. `JVGL106871001867753816`), the `preg_replace()` will **leave it unchanged** โ€” which is exactly what we want.

### โœ… Full Robust Example:

<?php
function normalizeCode($input) {
    return preg_replace('/^((w))/', '$1', $input);
}

// Test cases
$examples = [
    '(J)VGL106871001867753816',
    'JVGL106871001867753816',
    '(A)XYZ123456789',
    'XYZ123456789'
];

foreach ($examples as $example) {
    echo normalizeCode($example) . PHP_EOL;
}

### ๐Ÿงช Output:

JVGL106871001867753816
JVGL106871001867753816
AXYZ123456789
XYZ123456789

### โœ… Summary:
– If the string starts with a pattern like `(J)` โ†’ it removes the parentheses and merges.
– If the string is already formatted โ†’ no change is made.

Let me know if the prefix could contain more than one character or if you want to sanitize other patterns too.

User
[flatsome_blog_posts category_tabs='No' searchbox='No' pagination='No']
add_shortcode('flatsome_blog_posts', 'flatsome_blog_category_posts');

function flatsome_blog_category_posts($atts)
{
// Define shortcode attributes with defaults
$atts = shortcode_atts([
'cat_id' => 1126,
'pagination' => 'yes',
'columns' => 3,
'searchbox' => 'yes',
'category_tabs' => 'yes',
], $atts);
ob_start();
$terms = get_terms([
'taxonomy' => 'category',
'hide_empty' => true,
]);
echo $atts['pagination'];
if (!is_wp_error($terms))
{
$first_cat_id = intval($atts['cat_id']);
$args=['post_type' => 'post',
'posts_per_page' => 6,
'paged' => 1];
if($first_cat_id!=0)
$args['cat']=$first_cat_id;
$initial_query = new WP_Query($args);
$template_path = get_stylesheet_directory() . '/partials/blog-post-category-template.php';
if (file_exists($template_path)) {
include $template_path;
} else {
echo 'Template not found.';
}
}

return ob_get_clean();
}
above attributes not receiving

Assistant
The issue is that you're using `shortcode_atts()` correctly, but the attributes are not being passed **as lowercase** in the actual shortcode `[flatsome_blog_posts category_tabs='No' …]`. WordPress **automatically lowercases attribute keys** when passing them into the function. So, `'category_tabs'` becomes `'category_tabs'` (already lowercase) โ€” but `'No'` and `'Yes'` are values, and **you should check them case-insensitively**.

Also: you're echoing `$atts['pagination']` for debugging, which is good, but you should also ensure everything is working as expected with the attributes. Here's the fix:

### โœ… Fix: Make attribute values case-insensitive and debug correctly

add_shortcode('flatsome_blog_posts', 'flatsome_blog_category_posts');

function flatsome_blog_category_posts($atts)
{
    // Define shortcode attributes with defaults
    $atts = shortcode_atts([
        'cat_id'        => 1126,
        'pagination'    => 'yes',
        'columns'       => 3,
        'searchbox'     => 'yes',
        'category_tabs' => 'yes',
    ], $atts);

    // Normalize values (lowercase for easier comparison)
    $pagination    = strtolower($atts['pagination']) === 'yes';
    $searchbox     = strtolower($atts['searchbox']) === 'yes';
    $category_tabs = strtolower($atts['category_tabs']) === 'yes';
    $cat_id        = intval($atts['cat_id']);
    $columns       = intval($atts['columns']);

    ob_start();

    $terms = get_terms([
        'taxonomy' => 'category',
        'hide_empty' => true,
    ]);

    // Debug (optional)
    // var_dump($pagination, $searchbox, $category_tabs);

    if (!is_wp_error($terms)) {
        $args = [
            'post_type'      => 'post',
            'posts_per_page' => 6,
            'paged'          => 1,
        ];
        if ($cat_id !== 0) {
            $args['cat'] = $cat_id;
        }

        $initial_query = new WP_Query($args);

        // Pass values to template if needed
        $template_path = get_stylesheet_directory() . '/partials/blog-post-category-template.php';
        if (file_exists($template_path)) {
            include $template_path;
        } else {
            echo '<p>Template not found.</p>';
        }
    }

    return ob_get_clean();
}

### โœ… Usage:

[flatsome_blog_posts cat_id="0" pagination="No" searchbox="No" category_tabs="No" columns="2"]

### Optional Tip:
You can even pass these normalized values to the template:

include $template_path;
// OR make available:
$GLOBALS['flatsome_blog_settings'] = compact('pagination', 'searchbox', 'category_tabs', 'columns');

Let me know if you want tab/search UI logic in the PHP/HTML template too.

User
but we have also load ajax blog when click on category and using same blog template also for ajax
can you also allow how to no pagination is yes or no
Assistant
Great โ€” since you're using the **same blog template** for both initial load and AJAX responses, and you need to know whether `pagination="yes"` (or `"no"`), here's how to properly pass and handle the shortcode attributes **both in PHP and in AJAX**, while keeping the template reusable.

### โœ… Step-by-step Plan:

#### 1. **Pass normalized settings (pagination, searchbox, etc.) to the template**
Use `compact()` to bundle them into an array and pass them to the template.

#### 2. **Also make sure to pass them in AJAX (via JS)**
Youโ€™ll send `pagination=yes/no` and others to the AJAX handler too.

#### 3. **Inside template** (`blog-post-category-template.php`)
Check these flags like `$settings['pagination']` to show/hide pagination HTML.

### โœ… Updated Shortcode PHP:

add_shortcode('flatsome_blog_posts', 'flatsome_blog_category_posts');

function flatsome_blog_category_posts($atts)
{
    $atts = shortcode_atts([
        'cat_id'        => 1126,
        'pagination'    => 'yes',
        'columns'       => 3,
        'searchbox'     => 'yes',
        'category_tabs' => 'yes',
    ], $atts);

    $settings = [
        'pagination'    => strtolower($atts['pagination']) === 'yes',
        'searchbox'     => strtolower($atts['searchbox']) === 'yes',
        'category_tabs' => strtolower($atts['category_tabs']) === 'yes',
        'columns'       => intval($atts['columns']),
        'cat_id'        => intval($atts['cat_id']),
    ];

    ob_start();

    $terms = get_terms([
        'taxonomy' => 'category',
        'hide_empty' => true,
    ]);

    if (!is_wp_error($terms)) {
        $args = [
            'post_type'      => 'post',
            'posts_per_page' => 6,
            'paged'          => 1,
        ];
        if ($settings['cat_id'] !== 0) {
            $args['cat'] = $settings['cat_id'];
        }

        $initial_query = new WP_Query($args);
        $template_path = get_stylesheet_directory() . '/partials/blog-post-category-template.php';

        if (file_exists($template_path)) {
            include $template_path;
        } else {
            echo '<p>Template not found.</p>';
        }
    }

    return ob_get_clean();
}

### โœ… In `blog-post-category-template.php` Example:

<?php
// Make sure $initial_query and $settings are available

if (!empty($initial_query->posts)) :
    foreach ($initial_query->posts as $post) :
        setup_postdata($post);
        ?>
        <div class="blog-item"><?php the_title(); ?></div>
        <?php
    endforeach;
    wp_reset_postdata();
else :
    echo '<p>No posts found.</p>';
endif;

// Show pagination if enabled
if ($settings['pagination']) :
    ?>
    <div class="ajax-pagination">
        <!-- pagination links here -->
    </div>
<?php endif; ?>

### โœ… In JS AJAX call:
Send these values when loading by category:

$.ajax({
    url: ajaxurl,
    type: 'POST',
    data: {
        action: 'load_blog_posts_by_category',
        cat_id: clickedCatId,
        pagination: 'yes', // or 'no' based on current setting
        searchbox: 'no',
        category_tabs: 'no',
    },
    success: function (response) {
        $('#blog-container').html(response);
    }
});

### โœ… In AJAX PHP handler:
Use similar logic:

add_action('wp_ajax_load_blog_posts_by_category', 'load_blog_posts_by_category');
add_action('wp_ajax_nopriv_load_blog_posts_by_category', 'load_blog_posts_by_category');

function load_blog_posts_by_category() {
    $settings = [
        'pagination'    => strtolower($_POST['pagination'] ?? 'yes') === 'yes',
        'searchbox'     => strtolower($_POST['searchbox'] ?? 'yes') === 'yes',
        'category_tabs' => strtolower($_POST['category_tabs'] ?? 'yes') === 'yes',
        'columns'       => intval($_POST['columns'] ?? 3),
        'cat_id'        => intval($_POST['cat_id'] ?? 0),
    ];

    $args = [
        'post_type'      => 'post',
        'posts_per_page' => 6,
        'paged'          => 1,
    ];
    if ($settings['cat_id']) {
        $args['cat'] = $settings['cat_id'];
    }

    $initial_query = new WP_Query($args);
    $template_path = get_stylesheet_directory() . '/partials/blog-post-category-template.php';

    if (file_exists($template_path)) {
        include $template_path;
    } else {
        echo '<p>Template not found.</p>';
    }

    wp_die(); // for AJAX
}

Let me know if you want the pagination to support page numbers via AJAX (`paged`) as well โ€” I can include that logic too.

Leave a Comment

Your email address will not be published. Required fields are marked *