web-dev-qa-db-ja.com

関数のコンテンツにフィルターを適用する際にフィルターを無視する方法

投稿の上部に目次を追加するコンテンツ用のフィルターがあります。 Stack Exchange自体の答えから基本的な考え方を取り入れました。

次のようにフィルターを追加します。

add_filter('the_content', array('TableOfContents', 'writeTOC'), 100);

ここまでは問題ありませんが、問題は別の機能にあります。私のプラグインには、指定された投稿の最初の144文字を受け取り、それをメタ説明に変換する関数があります。上記のフィルターにより、メタ説明には私の投稿の実際のコンテンツが含まれていません。

        $meta = apply_filters('the_content', $post->post_content);
        $meta = strip_tags($meta);
        $meta = strip_shortcodes($meta );
        $meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
        $meta = substr($meta, 0, 144);

むしろ、私のメタ記述には目次を含む最初の144文字があります。

目次をメタディスクリプションから除外したいのですが、コードを再配置しても役に立ちませんでした。

以下に完全なコードを添付しました:

<?php
function Milyin_Head(){ 

global $post; 
if (!is_page()) {   
    if (!is_singular() ) {return; }
    elseif (!empty( $post->post_excerpt)) {
        $meta = $post->post_excerpt ;   
} 
    else {
        // THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....
        $meta = apply_filters('the_content', $post->post_content);
        $meta = strip_tags($meta);
        $meta = strip_shortcodes($meta );
        $meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
        $meta = substr($meta, 0, 175);
echo '<meta name="description" content="'. $meta . '"/>'; 
echo '<meta name="og:description" content="'. $meta . '"/>';
echo '<meta name="Twitter:description" content="'. $meta . '"/>';
}
}
else {
echo '<meta name="description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>'; 
echo '<meta name="og:description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';
echo '<meta name="Twitter:description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';

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


//This Function is Now Over, the Next Function Generates the Table Of Content

// Below is the Table Of Content Class, i added this for the sake of someone who wants to actually understand and in depth analyse my code. Its better to just move to bottom where i Apply The Filter

class TableOfContents {

    /**
     * Counts the occurence of header elements in Wordpress content
     * 
     * @param type $content
     * @return null|boolean|array
     */
    static function hasToc($tiers, $content) {

        $pattern = '/<h[1-' . $tiers . ']*[^>]*>(.*?)<\/h([1-' . $tiers . '])>/';
        $return = array();
        if (empty($content))
            return null;

        if (!preg_match_all($pattern, $content, $return)) {
            return false;
        }
        return $return;
    }

    /**
     * Generates a table of content only when singular pages are being viewed
     * 
     * @param type $tiers
     * @param type $text
     */
    static function generateTableOfContents($tiers, $content, $draw = TRUE, $return = array()) {

        if (!is_singular())
            return $content;


        $content = $toc . $content;
        $searches = array();
        $replaces = array();
        $return = (is_array($return) && !empty($return) ) ? $return : TableOfContents::hasToc($tiers, $content);

        if ($draw && !empty($return)):
             $toc = '<div class="Milyin-Container">';
            $toc .= "<span style=\"font-size:18px;\">Table of Contents</span>";
            $toc .= "<span style=\"float:right; width: 30px;height: 30px;margin: 5px;\" data-toggle=\"collapse\" data-target=\".list\">";
    $toc .= '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><g><path d="M491.318,235.318H20.682C9.26,235.318,0,244.577,0,256s9.26,20.682,20.682,20.682h470.636    c11.423,0,20.682-9.259,20.682-20.682C512,244.578,502.741,235.318,491.318,235.318z"/></g></g><g><g><path d="M491.318,78.439H20.682C9.26,78.439,0,87.699,0,99.121c0,11.422,9.26,20.682,20.682,20.682h470.636    c11.423,0,20.682-9.26,20.682-20.682C512,87.699,502.741,78.439,491.318,78.439z"/></g></g><g><g><path d="M491.318,392.197H20.682C9.26,392.197,0,401.456,0,412.879s9.26,20.682,20.682,20.682h470.636    c11.423,0,20.682-9.259,20.682-20.682S502.741,392.197,491.318,392.197z"/></g></g></svg></span>' ;
            $toc .= "<div class=\"list collapse\">";
            $toc .= "<ul class=\"parent start\">";
            $tags = reset($return);
            $titles = $return[1];
            $url = $return[1];
            $levels = end($return);
            $_level = 2;
            $chapters = array('0','0','0','0','0','0');

            $count = 0;
            foreach ($tags as $i => $htag) {
                $count++;
                $attributes = array();
                $href = $url[$i];
                    $href = strtolower($href);
                    strip_tags($href);
                    $href = preg_replace("/[^a-z0-9_\s-]/", "", $href);
                    $href = preg_replace("/[\s-]+/", " ", $href);
                    $href = preg_replace("/[\s_]/", "-", $href);


                $newId = 'id="' . $href . '"';
                $newhtag = $newId . '>';
                $htagr = str_replace('>' . $titles[$i], "\t" . $newhtag  . $titles[$i], $htag);
                $searches[] = $htag;
                $replaces[] = $htagr;


                if ((int)$levels[$i] === (int)$_level):
                        $chapters[$_level-1] = ((int)$chapters[$_level-1]+1);
                        $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1)  ) );
                        $toc .= '<li><span>' . strval($chapter) . '</span> <a href="#' . $href . '">' . $titles[$i] . '</a></li>';
                endif;

                if ($levels[$i] > $_level) {
                    $_steps = ((int) $levels[$i] - (int) $_level);

                    for ($j = 0; $j < $_steps; $j++):
                        $toc .= '<ol class="continue">';
                        $chapters[$levels[$i]-1+$j] = (int)$chapters[$levels[$i]-1+$j]+1;
                        $_level++;
                    endfor;
                    $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1)  ) );
                        $toc .= '<li><a href="#' . $href . '">' . $titles[$i] . '</a></li>';
                }

                if ($levels[$i] < $_level) {

                    $_steps = ((int) $_level - (int) $levels[$i]);
                    $chapters[$levels[$i]-1] = (int)$chapters[$levels[$i]-1]+1;
                    $_olevel = $_level;
                    for ($j = 0; $j < $_steps; $j++):
                        $chapters[$levels[$i]+$j] = 0;
                        $toc .= '</ol>';
                        $_level--;
                    endfor;

                    $chapters[$_olevel-1] = 0;
                    $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1)  ) );

                        $toc .= '<li><a href="#' . $href . '">' . $titles[$i] . '</a></li>';

                }
            }
            $toc .= '</ul>';
            $toc .= '</div></div><div class="clear"></div>';
            $content = str_replace($searches, $replaces, $content);
            $content = $toc . $content;
        endif;

        return $content;
    }

    /**
     * Appends the table of content to the $content
     * AKA. Executes our filter
     * 
     * @param type $content
     * @return type
     */
    static function writeToc($content) {

        $content = TableOfContents::generateTableOfContents(4, $content, TRUE);
        return $content;
    }

}

add_filter('the_content', array('TableOfContents', 'writeTOC'), 100);

// The Above Line Adds the Table Of Content Before The Post Content
// Problem is that in the first function of code, i want it to exclude this filter. I don't want the Table Of Content text to become my Meta Description


?>

3
Aditya Agarwal

一時的に関数をフックから切り離すことができます。

    // THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....

    $priority = has_filter('the_content', ['TableOfContents', 'writeTOC'] );
    if ( $priority !== false )
        remove_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );

    $meta = apply_filters('the_content', $post->post_content);

    if ( $priority !== false )
        add_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );


    $meta = strip_tags($meta);
    $meta = strip_shortcodes($meta );

Codex:

1
nmr

これを行うにはより良い方法があるかもしれませんが、プロセスの全範囲(ToC以外)を知らない場合、問題を解決する可能性のある迅速で簡単な方法を次に示します。

コンテンツがToC用にフィルターされる前に、後で取得できる変数に元のコンテンツを入れてみませんか?

私はあなたのコードを編集し、静的変数_$pre_toc_content_を追加しました。次に、generateTableOfContents()関数が実行されると、最初に他の処理が行われる前に、フィルタリングされていないコンテンツが変数に入れられます。

フィルタリングされた結果の代わりに、フィルタリングされていないコンテンツをピックアップして後で使用できます。

_    $meta = TableOfContents::$pre_toc_content;
    $meta = strip_tags($meta);
    $meta = strip_shortcodes($meta );
    $meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
    $meta = substr($meta, 0, 144);
_

変更を加えたコードは次のとおりです(比較的マイナーであり、それに応じてコメントされています)。

_<?php
function Milyin_Head(){ 

global $post; 
if (!is_page()) {   
    if (!is_singular() ) {return; }
    elseif (!empty( $post->post_excerpt)) {
        $meta = $post->post_excerpt ;   
} 
    else {
        // THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....
        // $meta = apply_filters('the_content', $post->post_content);

        // Trying it here with a static variable 
        $meta = TableOfContents::$pre_toc_content;

        // Or uncomment below to use a global variable
        global $global_pre_toc_content;
        // $meta = $global_pre_toc_content;

        $meta = strip_tags($meta);
        $meta = strip_shortcodes($meta );
        $meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
        $meta = substr($meta, 0, 175);
echo '<meta name="description" content="'. $meta . '"/>'; 
echo '<meta name="og:description" content="'. $meta . '"/>';
echo '<meta name="Twitter:description" content="'. $meta . '"/>';
}
}
else {
echo '<meta name="description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>'; 
echo '<meta name="og:description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';
echo '<meta name="Twitter:description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';

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


//This Function is Now Over, the Next Function Generates the Table Of Content

// Below is the Table Of Content Class, i added this for the sake of someone who wants to actually understand and in depth analyse my code. Its better to just move to bottom where i Apply The Filter

class TableOfContents {

    /**
     * A container for the unfiltered content.
     */
    static $pre_toc_content;

    /**
     * Counts the occurence of header elements in Wordpress content
     * 
     * @param type $content
     * @return null|boolean|array
     */
    static function hasToc($tiers, $content) {

        $pattern = '/<h[1-' . $tiers . ']*[^>]*>(.*?)<\/h([1-' . $tiers . '])>/';
        $return = array();
        if (empty($content))
            return null;

        if (!preg_match_all($pattern, $content, $return)) {
            return false;
        }
        return $return;
    }

    /**
     * Generates a table of content only when singular pages are being viewed
     * 
     * @param type $tiers
     * @param type $text
     */
    static function generateTableOfContents($tiers, $content, $draw = TRUE, $return = array()) {

        if (!is_singular())
            return $content;

        $content = $toc . $content;
        $searches = array();
        $replaces = array();
        $return = (is_array($return) && !empty($return) ) ? $return : TableOfContents::hasToc($tiers, $content);

        if ($draw && !empty($return)):
             $toc = '<div class="Milyin-Container">';
            $toc .= "<span style=\"font-size:18px;\">Table of Contents</span>";
            $toc .= "<span style=\"float:right; width: 30px;height: 30px;margin: 5px;\" data-toggle=\"collapse\" data-target=\".list\">";
    $toc .= '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><g><path d="M491.318,235.318H20.682C9.26,235.318,0,244.577,0,256s9.26,20.682,20.682,20.682h470.636    c11.423,0,20.682-9.259,20.682-20.682C512,244.578,502.741,235.318,491.318,235.318z"/></g></g><g><g><path d="M491.318,78.439H20.682C9.26,78.439,0,87.699,0,99.121c0,11.422,9.26,20.682,20.682,20.682h470.636    c11.423,0,20.682-9.26,20.682-20.682C512,87.699,502.741,78.439,491.318,78.439z"/></g></g><g><g><path d="M491.318,392.197H20.682C9.26,392.197,0,401.456,0,412.879s9.26,20.682,20.682,20.682h470.636    c11.423,0,20.682-9.259,20.682-20.682S502.741,392.197,491.318,392.197z"/></g></g></svg></span>' ;
            $toc .= "<div class=\"list collapse\">";
            $toc .= "<ul class=\"parent start\">";
            $tags = reset($return);
            $titles = $return[1];
            $url = $return[1];
            $levels = end($return);
            $_level = 2;
            $chapters = array('0','0','0','0','0','0');

            $count = 0;
            foreach ($tags as $i => $htag) {
                $count++;
                $attributes = array();
                $href = $url[$i];
                    $href = strtolower($href);
                    strip_tags($href);
                    $href = preg_replace("/[^a-z0-9_\s-]/", "", $href);
                    $href = preg_replace("/[\s-]+/", " ", $href);
                    $href = preg_replace("/[\s_]/", "-", $href);


                $newId = 'id="' . $href . '"';
                $newhtag = $newId . '>';
                $htagr = str_replace('>' . $titles[$i], "\t" . $newhtag  . $titles[$i], $htag);
                $searches[] = $htag;
                $replaces[] = $htagr;


                if ((int)$levels[$i] === (int)$_level):
                        $chapters[$_level-1] = ((int)$chapters[$_level-1]+1);
                        $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1)  ) );
                        $toc .= '<li><span>' . strval($chapter) . '</span> <a href="#' . $href . '">' . $titles[$i] . '</a></li>';
                endif;

                if ($levels[$i] > $_level) {
                    $_steps = ((int) $levels[$i] - (int) $_level);

                    for ($j = 0; $j < $_steps; $j++):
                        $toc .= '<ol class="continue">';
                        $chapters[$levels[$i]-1+$j] = (int)$chapters[$levels[$i]-1+$j]+1;
                        $_level++;
                    endfor;
                    $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1)  ) );
                        $toc .= '<li><a href="#' . $href . '">' . $titles[$i] . '</a></li>';
                }

                if ($levels[$i] < $_level) {

                    $_steps = ((int) $_level - (int) $levels[$i]);
                    $chapters[$levels[$i]-1] = (int)$chapters[$levels[$i]-1]+1;
                    $_olevel = $_level;
                    for ($j = 0; $j < $_steps; $j++):
                        $chapters[$levels[$i]+$j] = 0;
                        $toc .= '</ol>';
                        $_level--;
                    endfor;

                    $chapters[$_olevel-1] = 0;
                    $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1)  ) );

                        $toc .= '<li><a href="#' . $href . '">' . $titles[$i] . '</a></li>';

                }
            }
            $toc .= '</ul>';
            $toc .= '</div></div><div class="clear"></div>';
            $content = str_replace($searches, $replaces, $content);
            $content = $toc . $content;
        endif;

        return $content;
    }

    /**
     * Appends the table of content to the $content
     * AKA. Executes our filter
     * 
     * @param type $content
     * @return type
     */
    static function writeToc($content) {

        // Put original $content into a var you can pick up later
        self::$pre_toc_content = $content;

        // Or alternatively, use a global
        global $global_pre_toc_content;
        $global_pre_toc_content = $content;

        $content = TableOfContents::generateTableOfContents(4, $content, TRUE);
        return $content;
    }

}

add_filter('the_content', array('TableOfContents', 'writeTOC'), 100);

// The Above Line Adds the Table Of Content Before The Post Content
// Problem is that in the first function of code, i want it to exclude this filter. I don't want the Table Of Content text to become my Meta Description


?>
_
0
butlerblog