program development

Add expand/shrink functionality to WordPress article pages

Many times when we publish some articles on WordPress, they contain a lot of code. I generally don't like to compress the code and like […]

article directories

Many times when we publish some articles on WordPress, they contain a lot of code. I generally don't like to compress the code and like to format the code. However, formatting and displaying usually makes the article content look too much and is inconvenient for visitors to browse, so today I will introduce a function that can expand/shrink the article content.

Method:
1. Add the following code to header.php, or you can write it into a js file separately and introduce it in header.php. I introduced it.

1
2
3
4
5
6
7
<script type="text/javascript">
    jQuery(document).ready(function(jQuery) {
        jQuery('.collapseButton').click(function() {
            jQuery(this).parent().parent().find('.xContent').slideToggle('slow');
        });
    });
</script>

2. Add the following code to function.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
//展开收缩功能
function xcollapse($atts, $content = null){
    extract(shortcode_atts(array("title"=>""),$atts));
    return '<div style="margin: 0.5em 0;">
        <div class="xControl">
            <span class="xTitle">'.$title.'</span>
            <a href="javascript:void(0)" class="collapseButton xButton">展开/收缩</a>
            <div style="clear: both;"></div>
        </div>
        <div class="xContent" style="display: none;">'.$content.'</div>
    </div>';
}
add_shortcode('collapse', 'xcollapse');

3. You can optimize the code, because the default is to the left, which is not good to see. We ask it to display it in the middle, and the specific distance can be adjusted by yourself. Of course, it is okay to ignore this step.
Add the following code to style.css:

1
2
3
.xControl {
    padding-left: 32px;
}

4. Here is how to insert short code in the article

[collapse title="title"] Content that needs to be clicked to expand [/collapse]

to use this function. Among them, title refers to adding some prompts, of course, you can also omit title and not write it.